package com.ktgj.hotel.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.constant.HotelOrderStatus;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.AssistProductEnum;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.enums.HotelEnum;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.customer.api.domain.Coupon;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.hotel.common.ElongUtils;
import com.ktgj.hotel.domain.*;
import com.ktgj.hotel.domain.HotelOrder;
import com.ktgj.hotel.domain.base.*;
import com.ktgj.hotel.domain.common.HotelInfo;
import com.ktgj.hotel.domain.common.Hotels;
import com.ktgj.hotel.domain.dic.DicCity;
import com.ktgj.hotel.domain.dic.DicProvince;
import com.ktgj.hotel.domain.elong.*;
import com.ktgj.hotel.domain.enums.HotelChannelEnumDto;
import com.ktgj.hotel.domain.rooms.*;
import com.ktgj.hotel.domain.vo.*;
import com.ktgj.hotel.domain.vo.BankCardVo;
import com.ktgj.hotel.domain.vo.ContactVo;
import com.ktgj.hotel.domain.vo.OrderRoom;
import com.ktgj.hotel.mapper.HotelOrderMapper;
import com.ktgj.hotel.mapper.HotelOrderRoomMapper;
import com.ktgj.hotel.mapper.*;
import com.ktgj.hotel.utils.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import io.seata.common.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.hotel.service.IHotelService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import static com.ktgj.hotel.common.ElongUtils.getResult;

/**
 * 酒店Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-22
 */
@Service
public class HotelServiceImpl implements IHotelService {
    private static final Logger log = LoggerFactory.getLogger(HotelServiceImpl.class);

    private static String HOTEL = "hotel:";
    private static String ORDER = "order:";

    @Autowired
    private RedisService redisService;
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private HotelOrderMapper hotelOrderMapper;
    @Autowired
    private HotelInfoMapper hotelInfoMapper;
    @Autowired
    private HotelOrderRoomMapper hotelOrderRoomMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private DicSubwayStationMapper dicSubwayStationMapper;
    @Autowired
    private DicAirportStationMapper dicAirportStationMapper;
    @Autowired
    private DicHotPositionMapper dicHotPositionMapper;
    @Autowired
    private DicLankMarkMapper dicLankMarkMapper;
    @Autowired
    private HotelOrderPaydetailMapper hotelOrderPaydetailMapper;
    @Autowired
    private HotelOrderInvoiceMapper hotelOrderInvoiceMapper;
    @Autowired
    private HotelElongCityMapper hotelElongCityMapper;
    @Autowired
    private HotelSupplierLinkMapper hotelSupplierLinkMapper;
    @Autowired
    private DicThemsMapper dicThemsMapper;
    @Autowired
    private DicDistanceMapper dicDistanceMapper;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private DicReviewsMapper dicReviewsMapper;
    @Autowired
    private DicStarsMapper dicStarsMapper;
    @Autowired
    private DicAirportcityLinkMapper dicAirportcityLinkMapper;
    @Autowired
    private HotelOrdersourcetypeMapper hotelOrdersourcetypeMapper;
    @Autowired
    private HotelOrderoccupttypeMapper hotelOrderoccupttypeMapper;
    @Autowired
    private DicProvinceMapper dicProvinceMapper;
    @Autowired
    private HotelOrderFlowstatusMapper hotelOrderFlowstatusMapper;
    @Autowired
    private HotelOrderStatusMapper hotelOrderStatusMapper;
    @Autowired
    private RemotePayService remotePayService;
    @Autowired
    private HotelOrderRefundapplyMapper hotelOrderRefundapplyMapper;
    @Autowired
    private HotelOrderExceptionMapper hotelOrderExceptionMapper;
    @Autowired
    private DicCityMapper dicCityMapper;
    @Autowired
    private HotelOrderAssistMapper hotelOrderAssistMapper;

//    /**
//     * 查询酒店
//     * @param id 酒店ID
//     * @return 酒店
//     */
//    @Override
//    public Hotels selectHotelById(Long id) {
//        return hotelMapper.selectHotelById(id);
//    }
//
//    /**
//     * 查询酒店列表
//     * @param hotel 酒店
//     * @return 酒店
//     */
//    @Override
//    public List<Hotels> selectHotelList(Hotels hotel) {
//        return hotelMapper.selectHotelList(hotel);
//    }
//
//    /**
//     * 新增酒店
//     * @param hotel 酒店
//     * @return 结果
//     */
//    @Override
//    public int insertHotel(Hotels hotel) {
//        hotel.setCreateTime(DateUtils.getNowDate());
//        return hotelMapper.insertHotel(hotel);
//    }
//
//    /**
//     * 修改酒店
//     * @param hotel 酒店
//     * @return 结果
//     */
//    @Override
//    public int updateHotel(Hotels hotel) {
//        hotel.setUpdateTime(DateUtils.getNowDate());
//        return hotelMapper.updateHotel(hotel);
//    }
//
//    /**
//     * 批量删除酒店
//     * @param ids 需要删除的酒店ID
//     * @return 结果
//     */
//    @Override
//    public int deleteHotelByIds(Long[] ids) {
//        return hotelMapper.deleteHotelByIds(ids);
//    }
//
//    /**
//     * 删除酒店信息
//     * @param id 酒店ID
//     * @return 结果
//     */
//    @Override
//    public int deleteHotelById(Long id) {
//        return hotelMapper.deleteHotelById(id);
//    }

    /**
     * 根据条件查询酒店列表----李博洋已完成，该接口作废
     * @param input
     * @return
     */
    @Override
    public List<HotelOutput> selectHotelLists(HotelInput input) {
        String cacheObject = redisService.getCacheObject(HOTEL);
        if (cacheObject != null) {
            String str = JSON.toJSONString(cacheObject);
            String parse = JSON.parse(str).toString();
            List<HotelOutput> hotelOutput = JSONArray.parseArray(parse, HotelOutput.class);
            return hotelOutput;
        } else {
            List<HotelOutput> hotelOutputs = hotelMapper.selectHotelLists(input);
            if (hotelOutputs != null && hotelOutputs.size() > 0) {
                redisService.setCacheObject(HOTEL, JSON.toJSONString(hotelOutputs), 10L, TimeUnit.MINUTES);
            }
            return hotelOutputs;
        }
    }

    /**
     * 查询酒店房型信息
     * @param input
     * @return
     */
    @Override
    public HotelDetails queryByIdHotelDetail(HotelDetailInput input) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        input.Options = "1,2,3,4";
        double lowRateMin = 0;
        Hotels hotels = new Hotels();
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("type", "hotel");
        String coupon = remoteCustomerService.couponList(map).get(0).getCouponName();

        HotelDetails hotelDetails = new HotelDetails();
        if (hotelDetailOutput.Code.equals("0")) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                hotelDetails.HotelId = hotel.getHotelId();
                //将酒店接口返回的最低价格更新到数据库
                hotels.setBaseMinPrice(new BigDecimal(hotel.getLowRate()));
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    //将酒店接口返回的封面图更新到数据库
                    hotels.setPicPath(detailBean.getThumbNailUrl());
                    hotelMapper.updateHotel(hotels);
                }
                if (hotel.getRooms() != null) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                        RoomList rooms = new RoomList();
                        rooms.RoomId = room.getRoomId();
                        rooms.Name = room.getName();
                        rooms.ImageUrl = room.getImageUrl();
                        rooms.Description = room.getDescription();
                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                            Set<String> stringSet = new HashSet<>();
                            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.NightlyRatesBean nightlyRate : ratePlan.getNightlyRates()) {
                                if (nightlyRate.isStatus() == true && ratePlan.getStatus() == true) {
                                    if (stringSet.add(ratePlan.getRatePlanId() + String.valueOf(ratePlan.getTotalRate()))) {
                                        RoomRate roomRate = new RoomRate();
                                        roomRate.RatePlanId = ratePlan.getRatePlanId();
                                        roomRate.RoomTypeId = ratePlan.getRoomTypeId();
                                        roomRate.Coupon = coupon;
                                        roomRate.TotalRate = new BigDecimal(ratePlan.getTotalRate().setScale(0, BigDecimal.ROUND_UP).longValue());
                                        roomRate.RatePlanName = ratePlan.getRatePlanName();
                                        roomRate.PaymentType = ratePlan.getPaymentType();
                                        roomRate.mealCopyWriting = ratePlan.getMeals().getMealCopyWriting();
                                        rooms.RoomRates.add(roomRate);
                                    }
                                }
                            }
                        }
                        //取到房型的所有价格放到一个集合中，然后取最底的价格返回出去
                        List<Double> collect = rooms.RoomRates.stream().map(item ->
                                item.TotalRate.doubleValue()
                        ).collect(Collectors.toList());
                        Collections.sort(collect);
                        if (collect != null && collect.size() > 0){
                            lowRateMin = collect.get(0);
                        }
                        else {
                            lowRateMin = 0;
                        }

                        if (lowRateMin != 0){
                            rooms.LowRate = Math.ceil(lowRateMin);
                            hotelDetails.roomLists.add(rooms);
                        }
                    }
                }
            }
        }
        return hotelDetails;
    }

    /**
     * 后台查询酒店房型信息
     * */
    @Override
    public DetailsVo backByIdHotelDetail(HotelDetailInput input) throws Exception {
        DetailsVo detailsVo = new DetailsVo();
        detailsVo.conditionList = input.conditionList;
        input.Options = "1,2,3,4";
        HotelDetailOutput hotelDetailOutput;
        try {
            //调用同城接口
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        List<HotelDetailOutputVo> hotelDetailOutputVoList = hotelDetailOutputVo(hotelDetailOutput);

        List<String> roomIdList = new ArrayList<>();

        if (hotelDetailOutputVoList != null && hotelDetailOutputVoList.size() > 0){
            if (input.conditionList != null && input.conditionList.size() > 0){

                for (String condition : input.conditionList) {
                    for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList) {
                        for (RatePlansVo ratePlansVo : hotelDetailOutputVo.ratePlansVoList) {
                            //含早餐
                            if (condition.equals(HotelEnum.RegionalLocation.Breakfast.getValue())){
                                if (ratePlansVo.breakfast > 0){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //立即确认
                            else if (condition.equals(HotelEnum.RegionalLocation.Confirm.getValue())){
                                if (ratePlansVo.confirmNow){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //大床房
                            else if (condition.equals(HotelEnum.RegionalLocation.KingBedRoom.getValue())){
                                if (ratePlansVo.bedType.contains("大床")){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //双床房
                            else if (condition.equals(HotelEnum.RegionalLocation.DoubleBedRoom.getValue())){
                                if (ratePlansVo.bedType.contains("双床")){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //免费取消
                            else if (condition.equals(HotelEnum.RegionalLocation.Cancel.getValue())){
                                if (ratePlansVo.freeCancellation){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //可订
                            else if (condition.equals(HotelEnum.RegionalLocation.AvailableToOrder.getValue())){
                                if (ratePlansVo.availableToOrder){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //在线付款
                            else if (condition.equals(HotelEnum.RegionalLocation.Prepaid.getValue())){
                                if (ratePlansVo.paymentType.equals("预付")){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //到店付款
                            else if (condition.equals(HotelEnum.RegionalLocation.Collect.getValue())){
                                if (ratePlansVo.paymentType.equals("现付")){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //免费WI-FI上网
                            else if (condition.equals(HotelEnum.RegionalLocation.FreeWIFIInternet.getValue())){
                                if (hotelDetailOutputVo.freeInternet){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                            //免费有线宽带
                            else if (condition.equals(HotelEnum.RegionalLocation.FreeWiredBroadband.getValue())){
                                if (hotelDetailOutputVo.freeWiredBroadband){
                                    roomIdList.add(hotelDetailOutputVo.roomId);
                                }
                            }
                        }
                    }
                }
            }
            else {
                for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList) {
                    roomIdList.add(hotelDetailOutputVo.roomId);
                }
            }

            if (roomIdList != null && roomIdList.size() > 0){
                HashSet hashSet = new HashSet(roomIdList);
                roomIdList.clear();
                roomIdList.addAll(hashSet);

                List<HotelDetailOutputVo> hotelDetailOutputVos = new ArrayList<>();
                for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList) {
                    for (String roomId : roomIdList) {
                        if (roomId.equals(hotelDetailOutputVo.roomId)){
                            hotelDetailOutputVos.add(hotelDetailOutputVo);
                        }
                    }
                }

                List<HotelDetailsVo> hotelDetailsVoList = backHotelDetails(hotelDetailOutputVos, input);
                List<String> hotelFacilitiesList = new ArrayList<>();
                List<String> hotelPictureList = new ArrayList<>();

                for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                    detailsVo.setBasicInformation(hotel.getRooms().size() + "间客房");

//                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
//                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
//                            for (HotelDetailResponse.HotelsBean.PrepayRulesBean prepayRule : hotel.getPrepayRules()) {
//                                if (ratePlan.getPrepayRuleIds().equals(String.valueOf(prepayRule.getPrepayRuleId()))){
//                                    detailsVo.setEntryAndDepartureTime(prepayRule.getDescription());
//                                    break;
//                                }
//                            }
//                            if (detailsVo.getEntryAndDepartureTime() != null){
//                                break;
//                            }
//                        }
//                        if (detailsVo.getEntryAndDepartureTime() != null){
//                            break;
//                        }
//                    }

                    if (hotel.getFacilities() != null){
                        String[] strarrayList = hotel.getFacilities().split(",");
                        if (strarrayList != null && strarrayList.length > 0){
                            for (String strarray : strarrayList) {
                                switch (strarray){
                                    case "1":
                                        hotelFacilitiesList.add("免费wifi");
                                        break;
                                    case "2":
                                        hotelFacilitiesList.add("收费wifi");
                                        break;
                                    case "3":
                                        hotelFacilitiesList.add("免费宽带");
                                        break;
                                    case "4":
                                        hotelFacilitiesList.add("收费宽带");
                                        break;
                                    case "5":
                                        hotelFacilitiesList.add("免费停车场");
                                        break;
                                    case "6":
                                        hotelFacilitiesList.add("收费停车场");
                                        break;
                                    case "7":
                                        hotelFacilitiesList.add("免费接机服务");
                                        break;
                                    case "8":
                                        hotelFacilitiesList.add("收费接机服务");
                                        break;
                                    case "9":
                                        hotelFacilitiesList.add("室内游泳池");
                                        break;
                                    case "10":
                                        hotelFacilitiesList.add("室外游泳池");
                                        break;
                                    case "11":
                                        hotelFacilitiesList.add("健身房");
                                        break;
                                    case "12":
                                        hotelFacilitiesList.add("商务中心");
                                        break;
                                    case "13":
                                        hotelFacilitiesList.add("会议室");
                                        break;
                                    case "14":
                                        hotelFacilitiesList.add("酒店餐厅");
                                        break;
                                    case "15":
                                        hotelFacilitiesList.add("叫醒服务");
                                        break;
                                    case "16":
                                        hotelFacilitiesList.add("行李寄存");
                                        break;
                                    case "17":
                                        hotelFacilitiesList.add("双床");
                                        break;
                                    case "18":
                                        hotelFacilitiesList.add("大床");
                                        break;
                                }
                            }
                        }
                    }

                    for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                        detailsVo.hotelName = detailBean.getHotelName();
                        detailsVo.setPhone(detailBean.getPhone());
                        detailsVo.setAddress(detailBean.getAddress());
                        detailsVo.setFeatures(detailBean.getFeatures());

                        List<List<String>> generalAmenities = new ArrayList<>();
                        if (detailBean.getGeneralAmenities() != null && !detailBean.getGeneralAmenities().equals("")){
                            List<String> generalAmenitieList = new ArrayList<>();

                            //根据","拆分服务设施为数组
                            String[] split = detailBean.getGeneralAmenities().split(",");
                            if (split != null && split.length > 0){
                                //遍历服务设施数组
                                for (String s : split) {
                                    generalAmenitieList.add(s);
                                    //当内部集合的长度等于10时，把内部集合加入外部集合并清空内部集合
                                    if (generalAmenitieList.size() == 10){
                                        generalAmenities.add(generalAmenitieList);
                                        generalAmenitieList = new ArrayList<>();
                                    }
                                }

                                //处理拆分后的数组长度对10取余大于零，说明最后一组数据不能让内部数组长度等于10，遍历结束后进入判断加入外部集合
                                if (split.length % 10 > 0){
                                    generalAmenities.add(generalAmenitieList);
                                }
                            }
                            else {
                                generalAmenitieList.add(detailBean.getGeneralAmenities());
                                generalAmenities.add(generalAmenitieList);
                            }

                        }

                        detailsVo.setGeneralAmenities(generalAmenities);
                        detailsVo.setTraffic(detailBean.getTraffic());
                        detailsVo.setDescription(detailBean.getDescription());
                        for (HotelDetailResponse.HotelsBean.DetailBean.ReviewBean reviewBean : detailBean.getReview()) {
                            int i = reviewBean.getScore().indexOf("%");
                            if (i > 0){
                                detailsVo.setScore(reviewBean.getScore());
                            }
                            else {
                                detailsVo.setScore(reviewBean.getScore().substring(2) + "%");
                            }
                        }
                        for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                            if (image.getType() == 5){
                                for (HotelDetailResponse.HotelsBean.Images.Locations location : image.getLocations()) {
                                    if (location.getSizeType() == 10){
                                        if (hotelPictureList.size() < 3){
                                            hotelPictureList.add(location.getUrl());
                                        }
                                        else {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        detailsVo.setBusinessZoneName(detailBean.getBusinessZoneName());
                    }

                    detailsVo.setLowRate(hotel.getLowRate());
                }

                detailsVo.setHotelPictureList(hotelPictureList);
                detailsVo.setHotelFacilitiesList(hotelFacilitiesList);
                if (hotelDetailsVoList != null && hotelDetailsVoList.size() > 0){
                    detailsVo.setHotelDetailsVoList(hotelDetailsVoList);
                }
                else {
                    detailsVo.setHotelDetailsVoList(null);
                }
                return detailsVo;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("未查到数据");
        }
    }

    /**
     * 获取指定酒店房型条件信息
     * */
    public List<HotelDetailOutputVo> hotelDetailOutputVo(HotelDetailOutput hotelDetailOutput) throws Exception {
        List<HotelDetailOutputVo> hotelDetailOutputVoList = new ArrayList<>();

        List<HotelDetailResponse.HotelsBean.PrepayRulesBean> prepayRuleList = new ArrayList<>();
        List<HotelDetailResponse.HotelsBean.DetailBean> detailBeanList = new ArrayList<>();
        List<HotelDetailResponse.HotelsBean.RoomsBean> roomList = new ArrayList<>();
        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            prepayRuleList = hotel.getPrepayRules();
            detailBeanList = hotel.getDetail();
            roomList = hotel.getRooms();
        }
        for (HotelDetailResponse.HotelsBean.RoomsBean roomsBean : roomList) {
            HotelDetailOutputVo hotelDetailOutputVo = new HotelDetailOutputVo();
            hotelDetailOutputVo.hotelId = hotelDetailOutput.Result.getHotels().get(0).getHotelId();
            hotelDetailOutputVo.roomId = roomsBean.getRoomId();
            hotelDetailOutputVo.imageUrl = roomsBean.getImageUrl();
            hotelDetailOutputVo.name = roomsBean.getName();

            if (roomsBean.getBroadnet().equals("3")){
                hotelDetailOutputVo.freeInternet = true;
            }
            else {
                hotelDetailOutputVo.freeInternet = false;
            }

            if (roomsBean.getBroadnet().equals("1")){
                hotelDetailOutputVo.freeWiredBroadband = true;
            }
            else {
                hotelDetailOutputVo.freeWiredBroadband = false;
            }

            List<RatePlansVo> ratePlansVoList = new ArrayList<>();
            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlansBean : roomsBean.getRatePlans()) {
                RatePlansVo ratePlansVo = new RatePlansVo();
                ratePlansVo.breakfast = ratePlansBean.getNightlyRates().get(0).getBreakfastCount();
                ratePlansVo.bedType = roomsBean.getBedType();
                ratePlansVo.roomTypeId = ratePlansBean.getRoomTypeId();
                ratePlansVo.ratePlanId = ratePlansBean.getRatePlanId();
                if (ratePlansBean.getGuaranteeResult() != null){
                    if (ratePlansBean.getGuaranteeResult().getGuaranteeType() == 1){
                        ratePlansVo.arrivalTime = ratePlansBean.getGuaranteeResult().getArrivalTime();
                    }
                    else if (ratePlansBean.getGuaranteeResult().getGuaranteeType() == 2){
                        ratePlansVo.roomCount = ratePlansBean.getGuaranteeResult().getRoomCount();
                    }
                    else if (ratePlansBean.getGuaranteeResult().getGuaranteeType() == 3){
                        ratePlansVo.guaranteeType = "true";
                    }
                    else if (ratePlansBean.getGuaranteeResult().getGuaranteeType() == 4){
                        ratePlansVo.guaranteeType = "false";
                    }
                }
                else {
                    ratePlansVo.guaranteeType = "false";
                }

                if (roomsBean.getWindowType() != null && roomsBean.getWindowType().equals("有窗")){
                    ratePlansVo.windows = "true";
                }
                else {
                    ratePlansVo.windows = "false";
                }

                BigDecimal totalRate = new BigDecimal(-1);
                if (ratePlansBean.getTotalRate().compareTo(totalRate) == 0){
                    ratePlansVo.availableToOrder = false;
                }
                else {
                    ratePlansVo.availableToOrder = true;
                }
                if (ratePlansBean.getPaymentType().equals(HotelChannelEnumDto.PaymentType.SelfPay)){
                    ratePlansVo.paymentType = "现付";
                }
                else if (ratePlansBean.getPaymentType().equals(HotelChannelEnumDto.PaymentType.Prepay)){
                    ratePlansVo.paymentType = "预付";
                }
                else {
                    throw new Exception("付款类型不明");
                }
                ratePlansVo.price = ratePlansBean.getAverageRate();
                String priceStr = ratePlansVo.price.toString();
                if (priceStr.indexOf(".")!=-1)
                {
                    priceStr = priceStr.substring(0, priceStr.indexOf("."));
                    BigDecimal priceValue = new BigDecimal(priceStr);
                    if (ratePlansVo.price.compareTo(priceValue) == 1)
                    {
                        ratePlansVo.basePrice = ratePlansVo.price;
                        ratePlansVo.price = priceValue.add(new BigDecimal(1));
                    }
                }
                ratePlansVo.confirmNow = ratePlansBean.isInstantConfirmation();

                if (ratePlansBean.getPrepayResult() != null && ratePlansBean.getPrepayResult().getCancelType() == 1){
                    ratePlansVo.freeCancellation = true;
                }
                else {
                    ratePlansVo.freeCancellation = false;
                }
                ratePlansVo.ratePlanName = ratePlansBean.getRatePlanName();

                if (ratePlansBean.getPrepayResult() != null){
                    ratePlansVo.description = ratePlansBean.getPrepayResult().getCancelDescription();
                }

                ratePlansVoList.add(ratePlansVo);
            }
            hotelDetailOutputVo.ratePlansVoList = ratePlansVoList;
            hotelDetailOutputVoList.add(hotelDetailOutputVo);
        }

        for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList){
            hotelDetailOutputVo.hotelName = detailBeanList.get(0).getHotelName();
        }
        return hotelDetailOutputVoList;
    }

    /**
     * 后台酒店条件结果赋值
     * */
    public List<HotelDetailsVo> backHotelDetails(List<HotelDetailOutputVo> hotelDetailOutputVoList, HotelDetailInput input) throws Exception {
        List<HotelDetailsVo> hotelDetailsVoList = new ArrayList<>();
        for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList) {
            HotelDetailsVo hotelDetailsVo = new HotelDetailsVo();
            hotelDetailsVo.hotelId = hotelDetailOutputVo.hotelId;
            hotelDetailsVo.roomId = hotelDetailOutputVo.roomId;
            hotelDetailsVo.imageUrl = hotelDetailOutputVo.imageUrl;
            hotelDetailsVo.name = hotelDetailOutputVo.name;
            List<RatePlansOutPutVo> ratePlansOutPutVoList = new ArrayList<>();

            for (RatePlansVo ratePlansVo : hotelDetailOutputVo.ratePlansVoList){
                RatePlansOutPutVo ratePlansOutPutVo = new RatePlansOutPutVo();
                ratePlansOutPutVo.paymentType = ratePlansVo.paymentType;
                ratePlansOutPutVo.description = ratePlansVo.description;
                ratePlansOutPutVo.breakfast = ratePlansVo.breakfast;
                ratePlansOutPutVo.price = ratePlansVo.price;
                ratePlansOutPutVo.basePrice = ratePlansVo.basePrice;
                ratePlansOutPutVo.confirmNow = ratePlansVo.confirmNow;
                ratePlansOutPutVo.freeCancellation = ratePlansVo.freeCancellation;
                ratePlansOutPutVo.availableToOrder = ratePlansVo.availableToOrder;
                ratePlansOutPutVo.ratePlanName = ratePlansVo.ratePlanName;
                ratePlansOutPutVo.bedType = ratePlansVo.bedType;
                ratePlansOutPutVo.windows = ratePlansVo.windows;
                ratePlansOutPutVo.roomTypeId = ratePlansVo.roomTypeId;
                ratePlansOutPutVo.ratePlanId = ratePlansVo.ratePlanId;
                if (ratePlansVo.guaranteeType != null && !ratePlansVo.guaranteeType.equals("")){
                    ratePlansOutPutVo.guaranteeType = ratePlansVo.guaranteeType;
                }
                else if (ratePlansVo.roomCount != 0){
                    ratePlansOutPutVo.roomCount = ratePlansVo.roomCount;
                }
                else if (ratePlansVo.arrivalTime != null && !ratePlansVo.arrivalTime.equals("")){

                    try {
                        DateFormat format = new SimpleDateFormat("HH:mm");
                        Calendar latestArrivalTime = Calendar.getInstance();
                        latestArrivalTime.setTime(format.parse(input.LatestArrivalTime));//最晚到店时间
                        Calendar arrivalTime = Calendar.getInstance();
                        arrivalTime.setTime(format.parse(ratePlansVo.arrivalTime));//需要担保的到店时间
                        if (latestArrivalTime.compareTo(arrivalTime) == -1){
                            ratePlansOutPutVo.guaranteeType = "false";
                        }
                        else {
                            ratePlansOutPutVo.guaranteeType = "true";
                        }

                    } catch (Exception e){
                        throw new Exception("最晚到店时间格式错误");
                    }
                }

                ratePlansOutPutVoList.add(ratePlansOutPutVo);
            }
            hotelDetailsVo.ratePlansOutPutVos = ratePlansOutPutVoList;
            hotelDetailsVoList.add(hotelDetailsVo);
        }

        return hotelDetailsVoList;
    }

    /**
     * 查询酒店房型信息详情
     * @param input
     * @return
     */
    @Override
    public HotelDetailsList queryByIdHotelDetailsList(HotelDetailInput input) throws Exception {
        input.Options = "1,2,3,4";
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        HotelDetailsList hotelDetailsList = new HotelDetailsList();
        if (hotelDetailOutput.Code.equals("0")) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                RoomDetailList roomDetailList = new RoomDetailList();
                roomDetailList.LatestArrivalTime = input.LatestArrivalTime;
                hotelDetailsList.HotelId = hotel.getHotelId();
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    roomDetailList.GeneralAmenities = detailBean.getGeneralAmenities();
                }
                for (HotelDetailResponse.HotelsBean.PrepayRulesBean prepayRule : hotel.getPrepayRules()) {
                    if (prepayRule.getChangeRule().equals("PrepayNoChange")){
                        roomDetailList.Description = prepayRule.getChangeRule();
                        break;
                    }
                }
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                        roomDetailList.earliestToliveTime = ratePlan.getEarliestToliveTime();
                        roomDetailList.PayType = ratePlan.getPaymentType().toString();

                        //
                        if (ratePlan.getGuaranteeResult() != null && ratePlan.getPaymentType().toString().equals("SelfPay")){
                            //二进制位表示:1:到店时间担保,2:房量担保,3:预订即需担保,4:免担保
                            if (ratePlan.getGuaranteeResult().getGuaranteeType() == 4){
                                roomDetailList.Guarantee = "false";
                            }
                            else if (ratePlan.getGuaranteeResult().getGuaranteeType() == 3){
                                roomDetailList.Guarantee = "true";
                            }
                            else if (ratePlan.getGuaranteeResult().getGuaranteeType() == 2){

                            }
                        }

                        //todo 该酒店RoomTypeId 不对应
                        if (hotel.getHotelId().equals("50101471")){
                            //0007对应0468 0006没有对应值
                            input.RoomTypeId = "0468";

                        }

                        if (ratePlan.getRoomTypeId().equals(input.RoomTypeId)) {
                            for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                                if (image.getRoomId() != null){
                                    if (image.getType() == 8 && image.getRoomId().equals(room.getRoomId())) {
                                        for (HotelDetailResponse.HotelsBean.Images.Locations location : image.getLocations()) {
                                            Image images = new Image();
                                            images.ImageUrl = location.getUrl();
                                            if (roomDetailList.Images.size() > 9){
                                                break;
                                            }
                                            roomDetailList.Images.add(images);
                                        }
                                    }
                                }
                            }
                            roomDetailList.RatePlanId = ratePlan.getRatePlanId();
                            roomDetailList.RoomTypeId = ratePlan.getRoomTypeId();
                            roomDetailList.mealCopyWriting = ratePlan.getMeals().getMealCopyWriting();
                            roomDetailList.RoomId = room.getRoomId();
                            roomDetailList.Name = room.getName();
                            roomDetailList.Area = room.getArea();
                            roomDetailList.WindowType = room.getWindowType();
                            roomDetailList.Capcity = room.getCapcity();
                            roomDetailList.Broadnet = room.getBroadnet();
                            roomDetailList.Floor = room.getFloor();
                            roomDetailList.BedType = room.getBedType();
                        }
                    }
                }
                hotelDetailsList.roomLists = roomDetailList;
            }
        }
        return hotelDetailsList;
    }

    /**
     * 酒店房型页图片集合
     * @param input
     * @return
     */
    @Override
    public HotelRoomImagesResponse hotelRoomImages(HotelDetailInput input) throws Exception {
        //imageType为接口固定值
        int[] imageType = {1, 2, 3, 5, 6, 8, 10, 11, 12};
        HotelRoomImagesResponse response = new HotelRoomImagesResponse();
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (hotelDetailOutput.Code.equals("0")) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                    for (int i = 0; i < imageType.length; ++i) {
                        ImageList imageList = new ImageList();
                        imageList.setType(imageType[i]);
                        for (HotelDetailResponse.HotelsBean.Images.Locations location : image.getLocations()) {
                            if (imageType[i] == image.getType()) {
                                LocationList locationList = new LocationList();
                                locationList.setImageUrl(location.getUrl());
                                imageList.getLocationLists().add(locationList);
                            }
                        }
                        if (imageList.getLocationLists().size() > 0) {
                            response.getImageLists().add(imageList);
                        }
                    }
                }
            }
        }
        return response;
    }

    /**
     * 酒店房型页酒店信息
     * @param input
     * @return
     */
    @Override
    public HotelRoomInfoResponse hotelRoomInfo(HotelDetailInput input) throws Exception {
        HotelRoomInfoResponse response = new HotelRoomInfoResponse();
        Reviews reviews = hotelMapper.selectHotel(Long.valueOf(input.HotelIds));
        if (reviews != null) {
            response.getReviews().setCommentScore(reviews.getCommentScore());
            response.getReviews().setCommentCount(reviews.getCommentCount());
        }
        Facilities facilities = hotelInfoMapper.queryHotel(Long.valueOf(input.HotelIds));
        response.setFacilities(facilities);
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (hotelDetailOutput.Code.equals("0")) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    response.getHotelInfos().setHotelName(detailBean.getHotelName());
                    response.getHotelInfos().setLabelCategory(detailBean.getCategory());
                    response.getHotelInfos().setLabelStarRate(detailBean.getStarRate());
                    response.getHotelInfos().setAddress(detailBean.getAddress());
                    response.getHotelInfos().setLatitude(detailBean.getLatitude());
                    response.getHotelInfos().setLongitude(detailBean.getLongitude());
                }
                if (hotel.getRooms() != null) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                            if (ratePlan.getPromotionFlags() != null) {
                                for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.PromotionFlagBean promotionFlag : ratePlan.getPromotionFlags()) {
                                    response.getPromotion().setPromotionId(promotionFlag.getPromotionId());
                                    response.getPromotion().setPromotionTag(promotionFlag.getPromotionTag());
                                }
                            }
                        }
                    }
                }
            }
        }
        return response;
    }

    /**
     * 订单预定页-预定须知
     * @param input
     * @return
     */
    @Override
    public BookingInfo queryBooking(HotelDetailInput input) throws Exception {
        input.Options = "1,2,3,4";
        BookingInfo bookingInfo = new BookingInfo();
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }

        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            for (HotelDetailResponse.HotelsBean.BookingRulesBean bookingRule : hotel.getBookingRules()) {
                bookingInfo.setGeneralAmenities(bookingRule.getDescription());
            }
        }
        return bookingInfo;
    }

    /**
     * 填写订单
     * @param token
     * @param input
     * @return
     */
    @Override
    public OrderHotelOutput orderHotel(String token, OrderHotelInput input) {
        input.Options = "1,2,3,4";
        OrderHotelOutput orderHotelOutput = new OrderHotelOutput();
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        R<Customer> loginCustomerByToken = remoteCustomerService.getLoginCustomerByToken(token);
        try {
            if (input.passengerLists != null && input.passengerLists.size() > 0){
                for (PassengerLists passengerList : input.passengerLists) {
                    Long customerId = loginCustomerByToken.getData().getCustomerId();
                    List<CommonPassengerApi> commonPassengerApis = remoteCustomerService.queryPassengerByCustomerId(customerId, passengerList.commonTrvelersId, passengerList.certificateType);
                    for (CommonPassengerApi passengerApi : commonPassengerApis) {
                        CheckPassenger checkPassenger = new CheckPassenger();
                        checkPassenger.passengerId = passengerApi.getCommonTrvelersId();
                        checkPassenger.passengerName = passengerApi.getChineseName();
                        orderHotelOutput.checkInfo.passenger.add(checkPassenger);
                    }
                }
            }

            hotelDetailInput.ArrivalDate = input.ArrivalDate;
            hotelDetailInput.DepartureDate = input.DepartureDate;
            hotelDetailInput.HotelIds = input.HotelIds;
            hotelDetailInput.RoomTypeId = input.RoomTypeId;

            hotelDetailInput.Options = input.Options;
            if (input.roomNum != null && !input.roomNum.equals("")){
                orderHotelOutput.checkInfo.roomNum = input.roomNum;
            }

            if (input.phone != null && !input.phone.equals("")){
                orderHotelOutput.checkInfo.phone = input.phone;
            }

            if (input.toTime != null && !input.toTime.equals("")){
                orderHotelOutput.checkInfo.toTime = input.toTime;
            }

            HotelDetailOutput hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                orderHotelOutput.hotelLists.HotelId = hotel.getHotelId();
                orderHotelOutput.hotelLists.ArrivalDate = input.ArrivalDate;
                orderHotelOutput.hotelLists.DepartureDate = input.DepartureDate;
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    orderHotelOutput.hotelLists.HotelName = detailBean.getHotelName();
                    orderHotelOutput.address = detailBean.getAddress();
                }
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                        if (ratePlan.getRatePlanId() == input.RatePlanId){
                            orderHotelOutput.hotelLists.RoomId = room.getRoomId();
                            orderHotelOutput.hotelLists.Name = room.getName();
                            orderHotelOutput.hotelLists.WindowType = room.getWindowType();
                            orderHotelOutput.hotelLists.BedType = room.getBedType();
                            orderHotelOutput.hotelLists.mealCopyWriting = ratePlan.getMeals().getMealCopyWriting();
                            orderHotelOutput.hotelLists.LowRate = new BigDecimal(ratePlan.getTotalRate().setScale(0, BigDecimal.ROUND_UP).longValue());
                            orderHotelOutput.hotelLists.floor = room.getFloor();
                            orderHotelOutput.hotelLists.area = room.getArea();
                            orderHotelOutput.hotelLists.capcity = room.getCapcity();
                        }
                    }
                }
            }
            R<Long> depositBusinessByToken = remoteCustomerService.queyUserDepositBusinessByToken(token);
            orderHotelOutput.depositBusiness = depositBusinessByToken.getData();
            //积分
            R<Long> points = remoteCustomerService.queyUserCreditsNumByToken(token);
            if (points.getData() != null) {
                Long pointsData = points.getData();
                orderHotelOutput.points = pointsData;
            }

            if (input.price != null && !input.price.equals("")){
                //优惠券
                R<CouponDto> couponDtoR = remoteCustomerService.queyUserCouponByToken(token, input.price);
                if (couponDtoR != null) {
                    orderHotelOutput.coupon = couponDtoR.getData();
                }
            }

            //辅营产品
            Map<String, Object> map = new HashMap<>();
            map.put("status", AssistProductEnum.activation.getValue());
            map.put("businessType", AssistProductEnum.hotel.getValue());
            List<AssistProductApi> assistProductApis = remoteCustomerService.queryAssistProductList(map);
            orderHotelOutput.assistProduct = assistProductApis;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderHotelOutput;
    }

    /**
     * 酒店创建订单（艺龙）参数赋值
     * */
    public HotelOrder assign(HotelDetailOutput hotelDetailOutput, CreateHotelOrder condition, Customer customer, CustomerCard customerCard) throws Exception {
        HotelOrder hotelOrder = new HotelOrder();
        hotelOrder.setOrdertype(condition.orderType);

        if (hotelDetailOutput != null) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    condition.HotelName = detailBean.getHotelName();
                    hotelOrder.setHoteladdress(detailBean.getAddress());
                    hotelOrder.setHotelphone(detailBean.getPhone());
                    hotelOrder.setProvinceid(detailBean.getCity());
                    hotelOrder.setCityid(detailBean.getCity());
                    hotelOrder.setHotelstar(detailBean.getStarRate());
                }
                if (hotel.getRooms() != null && hotel.getRooms().size() > 0){
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                            hotelOrder.setHotelcode(ratePlan.getHotelCode());
                            HotelChannelEnumDto.PaymentType paymentType = ratePlan.getPaymentType();
                            // todo
//                        if (paymentType.getValue().equals(HotelEnum.RegionalLocation.Prepay.getValue())){
//                            hotelOrder.setOrdertype(3l);//预付
//                            hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.Prepay.getValue());
//                        }
//                        else {//现付
//                            if (ratePlan.getGuaranteeResult().getGuaranteeType() == 4){
//                                hotelOrder.setOrdertype(1l);//现付
//                                hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.SelfPay.getValue());
//                            }
//                            else if (ratePlan.getGuaranteeResult().getGuaranteeType() == 3){
//                                hotelOrder.setOrdertype(2l);//担保
//                                hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.Guarantee.getValue());
//                            }
//                            else if (ratePlan.getGuaranteeResult().getGuaranteeType() == 2){
//                                //用户预订间数小于此值不需要担保，否则需要担保
//                                if (condition.NumberOfRooms < ratePlan.getGuaranteeResult().getRoomCount()){
//                                    hotelOrder.setOrdertype(1l);//现付
//                                    hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.SelfPay.getValue());
//                                }
//                                else {
//                                    hotelOrder.setOrdertype(2l);//担保
//                                    hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.Guarantee.getValue());
//                                }
//                            }
//                            else if (ratePlan.getGuaranteeResult().getGuaranteeType() == 1){
//                                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
//                                Date latestArrivalTime = format.parse(condition.LatestArrivalTime);
//                                Date arrivalTime = format.parse(ratePlan.getGuaranteeResult().getArrivalTime());
//                                //用户填写的最晚到店早于此时间不需要担保，否则需要担保
//                                if (latestArrivalTime.compareTo(arrivalTime) < 0){
//                                    hotelOrder.setOrdertype(1l);//现付
//                                    hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.SelfPay.getValue());
//                                }
//                                else {
//                                    hotelOrder.setOrdertype(2l);//担保
//                                    hotelOrder.seteLongOrdertype(HotelEnum.RegionalLocation.Guarantee.getValue());
//                                }
//                            }
//                        }
                        }
                    }
                }
                else {
                    throw new Exception("未查到该酒店房型信息");
                }
            }
        } else {
            hotelOrder.setHoteladdress(condition.address);
            hotelOrder.setHotelphone(condition.phone);
            List<DicCity> areaId = dicCityMapper.areaId(condition.cityName);
            if (areaId != null && areaId.size() > 0) {
                hotelOrder.setProvinceid(String.valueOf(areaId.get(0).getProvinceId()));
                hotelOrder.setCityid(String.valueOf(areaId.get(0).getId()));
            }

            hotelOrder.setHotelstar(condition.hotelstar);
        }

        if (condition.AffiliateConfirmationId != null){
            hotelOrder.setSupplierorderid(condition.AffiliateConfirmationId);
            hotelOrder.setELongOrderId(Long.valueOf(condition.AffiliateConfirmationId));
        }
        hotelOrder.setAgentid(0L);
        hotelOrder.setOpemployeeid(788L);
        hotelOrder.setOrdersourcetypeid(1L);
        hotelOrder.setHotelid(condition.HotelId);
        hotelOrder.setOrderversion("1");
        hotelOrder.setHotelname(condition.HotelName);
        hotelOrder.setRegionid(0L);
        hotelOrder.setPayAmount(condition.payAmount);
        hotelOrder.setOrderstatusid(HotelOrderStatus.Status.TOBECONFIRMED.getCode());
        hotelOrder.setOrderflowstatusid(HotelOrderStatus.FlowStatus.TOBEPAID.getCode());
        hotelOrder.setCustomerid(customer.getCustomerId());
        hotelOrder.setCustomercardid(customerCard.getCardCode());
        hotelOrder.setArrivetime(condition.ArrivalDate);
        hotelOrder.setCheckouttime(condition.DepartureDate);
        hotelOrder.setCreateTime(new Date());
        hotelOrder.setOrderoccupttypeid(1L);
        for (Guest contact : condition.Customers) {
            hotelOrder.setEmployeename(contact.name);
            break;
        }
        hotelOrder.setCustomername(customer.getCustomerName());
        hotelOrder.setIsdelete("false");
        hotelOrder.setPhone(condition.Mobile);
        hotelOrder.setNumberOfRooms(condition.NumberOfRooms);
        if (condition.points != null) {
            hotelOrder.setPoints(new BigDecimal(condition.points));
        }else
            {
                hotelOrder.setPoints(new BigDecimal(0));
        }
        if (condition.couponId != null && condition.couponId != 0) {
            hotelOrder.setCouponID(condition.couponId);
            R<Coupon> coupon = remoteCustomerService.couponById(condition.couponId);
            if (coupon.getData().getCouponType().equals("CouponTypeFullMinus") || coupon.getData().getCouponType().equals("CouponTypeCashCoupon")) {
                hotelOrder.setCouponAmount(coupon.getData().getCouponPrice());
            } else {
                BigDecimal price = coupon.getData().getCouponDiscount();
                BigDecimal divide = price.divide(new BigDecimal(100));
                BigDecimal countPrice = condition.totalsalePrice.multiply(divide);
                BigDecimal couponAmount = condition.totalsalePrice.subtract(countPrice);
                hotelOrder.setCouponAmount(couponAmount);
            }
        }
        if (condition.usedDeposit != null) {
            hotelOrder.setDepositAmount(condition.usedDeposit);
        }

        return hotelOrder;
    }

    /**
     * 酒单创建订单（数据库）
     * */
    @Transactional
    @Override
    public HotelIdNumVo order(String token, CreateHotelOrder condition, Long customerId, HotelDetailOutput hotelDetailOutput) throws Exception {
        HotelIdNumVo hotelIdNumVo = new HotelIdNumVo();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        Date date = new Date();
        String dateNew = format.format(date);
        String newDate = dateFormat.format(date);

        condition = createHotelOrder(hotelDetailOutput, condition, token, customerId);
        CreateHotelOrderVo hotelOrderVo = createHotelOrderVo(condition);
        CalculationDTO calculationDTO = null;

        //App
        if (customerId == null || customerId == 0 && condition.PaymentType.equals("Prepay")){
            CalculationVOApi calculationVOApi = new CalculationVOApi();
            List<BigDecimal> prices = new ArrayList<>();
            prices.add(hotelOrderVo.TotalPrice);
            calculationVOApi.setPrices(prices);//商品单价集合
            calculationVOApi.setAmount(hotelOrderVo.NumberOfCustomers);//商品数量
            List<BigDecimal> additionalPrices = new ArrayList<>();
            if (hotelOrderVo.productamount != null && hotelOrderVo.productamount.size() > 0){
                for (AssistProductVoApi assistProductVoApi : hotelOrderVo.productamount) {
                    if (assistProductVoApi.getSalePrice()!=null)
                    {
                        if (assistProductVoApi.getProductCount()>1)
                        {
                            for (int i = 0; i < assistProductVoApi.getProductCount(); i++)
                            {
                                additionalPrices.add(assistProductVoApi.getSalePrice());
                            }
                        }else
                        {
                            additionalPrices.add(assistProductVoApi.getSalePrice());
                        }
                    }
                }
            }

            calculationVOApi.setAdditionalPrices(additionalPrices);//附加商品单价集合
            calculationVOApi.setAdditionalAmount(hotelOrderVo.NumberOfCustomers);//附加商品数量
            calculationVOApi.setCouponId(hotelOrderVo.couponId);//优惠卷id
            calculationVOApi.setDepositAmount(hotelOrderVo.usedDeposit);//用户拥有的金币数量
            calculationVOApi.setUseDeposit(hotelOrderVo.useDeposit);//是否使用金币
            //用户拥有的积分数量
            if (hotelOrderVo.points==null)
            {
                calculationVOApi.setPointAmount(0);
            }else {
                calculationVOApi.setPointAmount(Integer.valueOf(hotelOrderVo.points.toString()));
            }
            calculationVOApi.setUsePoint(hotelOrderVo.usePoint);//是否使用积分
            BigDecimal calcSum = new BigDecimal(0);
            calcSum = calcSum.add(hotelOrderVo.totalsalePrice);
//            for (int i = 0; i < additionalPrices.size(); i++)
//            {
//                calcSum = calcSum.add(additionalPrices.get(i));
//            }
            calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
            if (calculationDTO.getPrice().compareTo(calcSum) != 0){
                throw new Exception("支付金额发生变化");
            }
        }
        //Crm
        else if (customerId == null || customerId != 0 && condition.PaymentType.equals("Prepay")){
            CalculationVOApi calculationVOApi = new CalculationVOApi();
            List<BigDecimal> prices = new ArrayList<>();
            prices.add(hotelOrderVo.TotalPrice);
            calculationVOApi.setPrices(prices);//商品单价集合
            calculationVOApi.setAmount(hotelOrderVo.NumberOfCustomers);//商品数量
            List<BigDecimal> additionalPrices = new ArrayList<>();
            if (hotelOrderVo.productamount != null && hotelOrderVo.productamount.size() > 0){
                for (AssistProductVoApi assistProductVoApi : hotelOrderVo.productamount) {
                    if (assistProductVoApi.getSalePrice()!=null)
                    {
                        if (assistProductVoApi.getProductCount()>1)
                        {
                            for (int i = 0; i < assistProductVoApi.getProductCount(); i++)
                            {
                                additionalPrices.add(assistProductVoApi.getSalePrice());
                            }
                        }else
                        {
                            additionalPrices.add(assistProductVoApi.getSalePrice());
                        }
                    }
                }
            }
            calculationVOApi.setAdditionalPrices(additionalPrices);//附加商品单价集合
            if (additionalPrices != null && additionalPrices.size() > 0){
                calculationVOApi.setAdditionalAmount(hotelOrderVo.NumberOfCustomers);//附加商品数量
            }
            else {
                calculationVOApi.setAdditionalAmount(0);//附加商品数量
            }
            calculationVOApi.setCouponId(0l);//优惠卷id
            calculationVOApi.setDepositAmount(condition.amount);//用户拥有的金币数量
            calculationVOApi.setUseDeposit(hotelOrderVo.useDeposit);//是否使用金币
            //用户拥有的积分数量
            if (hotelOrderVo.points==null)
            {
                calculationVOApi.setPointAmount(0);
            }else {
                calculationVOApi.setPointAmount(Integer.valueOf(hotelOrderVo.points.toString()));
            }
            calculationVOApi.setUsePoint(false);//是否使用积分
            if (condition.AffiliateConfirmationId == null) {
                calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
                BigDecimal calcSum = new BigDecimal(0);
                calcSum = calcSum.add(hotelOrderVo.totalsalePrice);
                for (int i = 0; i < additionalPrices.size(); i++)
                {
                    calcSum = calcSum.add(additionalPrices.get(i));
                }
                if (calculationDTO.getPrice().compareTo(calcSum) != 0){
                    throw new Exception("支付金额发生变化");
                }
            }
        }

        R<Customer> customer;
        if (customerId == null || customerId == 0){
            customer = remoteCustomerService.getLoginCustomerByToken(token);
        }
        else {
            customer = remoteCustomerService.getCustomerId(customerId);
        }

        if (customer.getData() == null){
            throw new Exception("会员信息未更新，请重新登录");
        }
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());

        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards = customerCards.stream().sorted(Comparator.comparing(CustomerCard::getCardLevel).reversed()).collect(Collectors.toList());
        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);

        HotelOrder hotelOrder = new HotelOrder();
        if (hotelDetailOutput != null) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                if (hotel.getDetail() != null && hotel.getDetail().size() > 0) {
                    for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                        if (detailBean.getStarRate() != 0) {
                            switch (detailBean.getStarRate()) {
                                case 1:
                                    hotelOrder.setHotelstar(8);
                                    break;
                                case 2:
                                    hotelOrder.setHotelstar(9);
                                    break;
                                case 3:
                                    hotelOrder.setHotelstar(5);
                                    break;
                                case 4:
                                    hotelOrder.setHotelstar(3);
                                    break;
                                case 5:
                                    hotelOrder.setHotelstar(1);
                                    break;
                            }
                        } else {
                            switch (detailBean.getCategory()) {
                                case 0:
                                case 1:
                                case 2:
                                    hotelOrder.setHotelstar(7);
                                    break;
                                case 3:
                                    hotelOrder.setHotelstar(6);
                                    break;
                                case 4:
                                    hotelOrder.setHotelstar(4);
                                    break;
                                case 5:
                                    hotelOrder.setHotelstar(2);
                                    break;
                            }
                        }
                    }
                }
            }
        } else {
            hotelOrder.setHotelstar(condition.hotelstar);
        }
        SnowFlake snowFlake = new SnowFlake(31, 31);
        Long orderNum = snowFlake.nextId();
        hotelOrderVo.AffiliateConfirmationId = orderNum.toString();

        if (customerCardR.equals("") || customerCardR == null){
            throw new Exception("该会员没有可使用的银行卡");
        }


        try {
            hotelOrder = assign(hotelDetailOutput, condition, customer.getData(), customerCardR);
            hotelOrder.setOpemployeeid(1l);

            if (condition.sourceTypeName != null && !condition.sourceTypeName.equals("")){
                hotelOrder.setSourceWay(condition.sourceTypeName);
            }
            else {
                throw new Exception("订单渠道不能为空");
            }

            hotelOrder.setPlusmoneystatus(CustomerConstants.waitPay.getValue());
            hotelOrder.setHotelid(condition.HotelId);
            hotelOrder.setOrderversion("1");
            hotelOrder.setHotelname(condition.HotelName);
            hotelOrder.setHoteladdress(condition.address);
            hotelOrder.setHotelphone(condition.phone);

            /*DicProvince dicProvince = dicProvinceMapper.selectDicProvinceByProvinceName(condition.cityName + "%");

            hotelOrder.setCityid(dicProvince.getId().toString());*/
            hotelOrder.setOrderstatusid(1l);
            hotelOrder.setOrderflowstatusid(1l);

//            List<HotelSupplierLink> hotelSupplierLinks = hotelSupplierLinkMapper.selectHotelSupplierLinkByHotelId(condition.HotelId);
//            HotelSupplierLink hotelSupplierLink;
//            if (hotelSupplierLinks.size() > 1){
//                for (HotelSupplierLink supplierLink : hotelSupplierLinks) {
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(supplierLink.getCreateTime());
//                    supplierLink.setMillisecond(calendar.getTimeInMillis());
//                }
//                hotelSupplierLinks.sort((y, x) -> Double.compare(y.getMillisecond(), x.getMillisecond()));
//            }
//            hotelSupplierLink = hotelSupplierLinks.get(0);
            if (condition.hotelEnum != null && !condition.hotelEnum.equals("")){
                hotelOrder.setSupplierid(condition.hotelEnum);
            }
            else {
                throw new Exception("酒店供应商枚举不能为空，枚举参数由酒店列表返回");
            }
            hotelOrder.setCustomerid(customer.getData().getCustomerId());

            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customer.getData().getCustomerId());

            CustomerCard customerCard = remoteCustomerService.customerCardList(map);

            hotelOrder.setCardtypeid(customerCard.getCardId());
            hotelOrder.setCustomercardid(customerCard.getCardCode());
            hotelOrder.setArrivetime(condition.ArrivalDate);
            hotelOrder.setCheckouttime(condition.DepartureDate);
            //预付
            if (condition.PaymentType.equals(HotelEnum.RegionalLocation.Prepay.getValue())){
                hotelOrder.setOrdertype(3l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待支付.getValue());
            }
            //现付
            else if (condition.PaymentType.equals(HotelEnum.RegionalLocation.SelfPay.getValue())){
                hotelOrder.setOrdertype(1l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待核实入住.getValue());
            }
            //担保
            else if (condition.PaymentType.equals(HotelEnum.RegionalLocation.Guarantee.getValue())){
                hotelOrder.setOrdertype(2l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待担保.getValue());
            }
            else {
                throw new Exception("支付类型错误");
            }
            hotelOrder.setCustomername(customer.getData().getCustomerName());
            hotelOrder.setIsdelete("false");

            hotelOrder.setCreateTime(dateFormat.parse(newDate));

            hotelOrder.setNumberOfRooms(condition.NumberOfRooms);
            // todo 测试金额写死
            String pay = "0.1";
            hotelOrder.setElongPayAmount(condition.basePrice);
            hotelOrder.setPayAmount(new BigDecimal(pay));
//            hotelOrder.setPayAmount(hotelOrderVo.totalsalePrice);

            Calendar arrivalDate = Calendar.getInstance();
            Calendar departureDate = Calendar.getInstance();
            arrivalDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(condition.ArrivalDate));
            departureDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(condition.DepartureDate));
            long i = departureDate.getTimeInMillis() - arrivalDate.getTimeInMillis();
            i = i / 1000 / 60 / 60 / 24;
            if (i <= 0){
                i = 1;
            }
            hotelOrder.setCheckInTime(i);
            hotelOrder.setLatestArrivalTime(condition.LatestArrivalTime);
            hotelOrder.setEarliestArrivalTime(condition.EarliestArrivalTime);
            hotelOrder.setPhone(condition.Mobile);
            hotelOrder.setRatePlanId(condition.RatePlanId.toString());
            hotelOrder.setOrderNum(orderNum.toString());
            if (token != null) {
                hotelOrder.setSourceWay("App");
            } else {
                hotelOrder.setSourceWay("Crm");
            }
            if (hotelOrder.geteLongOrdertype() != null){
                switch (hotelOrder.geteLongOrdertype()){
                    case "Prepay":
                        hotelOrder.setOrdertype(3l);
                        break;
                    case "SelfPay":
                        hotelOrder.setOrdertype(1l);
                        break;
                }
            }
            else if (condition.bankCardNum != null && !condition.bankCardNum.equals("")){
                    hotelOrder.setOrdertype(2l);
                    hotelOrder.setBackCardNum(condition.bankCardNum);
            }
            // todo 测试专用
            hotelOrder.setOrdertype(3l);
        } catch (Exception e){
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }

        int insertHotelOrder = hotelOrderMapper.insertHotelOrder(hotelOrder);


        if (condition.AffiliateConfirmationId == null) {
            //新增支付信息
            HotelOrderPaydetail hotelOrderPaydetail = new HotelOrderPaydetail();
            if (condition.PaymentType.equals("Prepay")){
                hotelOrderPaydetail.setRemittanceprice(hotelOrderVo.TotalPrice.multiply(new BigDecimal(hotelOrderVo.NumberOfCustomers)));
                for (DiscountDescDTOApi item : calculationDTO.getActualPriceDetailed().getDiscountDesc()) {

                    if (item.getDesc().equals("优惠券")) {
                        if (hotelOrderVo.usePoint) {
                            hotelOrderPaydetail.setPaymoney(item.getPrice());
                        }
                        else {
                            hotelOrderPaydetail.setPaymoney(new BigDecimal(0));
                        }
                    }
                    if (item.getDesc().equals("金币")) {
                        if (hotelOrderVo.useDeposit){
                            hotelOrderPaydetail.setDepositmoney(item.getPrice());
                        }
                        else {
                            hotelOrderPaydetail.setDepositmoney(new BigDecimal(0));
                        }
                    }
                }

                if (hotelOrderVo.productamount != null && hotelOrderVo.productamount.size() > 0){
                    BigDecimal salePrice = new BigDecimal(0);
                    for (AssistProductVoApi assistProductVoApi : hotelOrderVo.productamount) {
                        salePrice.add(assistProductVoApi.getSalePrice());
                    }
                    hotelOrderPaydetail.setAmount(salePrice.multiply(new BigDecimal(hotelOrderVo.NumberOfRooms)));
                }
                else {
                    hotelOrderPaydetail.setAmount(new BigDecimal(0));
                }
                hotelOrderPaydetail.setOrdertype(2l);
                hotelOrderPaydetail.setAmount2(calculationDTO.getPrice());
            }
            else {
                hotelOrderPaydetail.setRemittanceprice(new BigDecimal(0));
                hotelOrderPaydetail.setPaymoney(new BigDecimal(0));
                hotelOrderPaydetail.setDepositmoney(new BigDecimal(0));
                hotelOrderPaydetail.setAmount(new BigDecimal(0));
                hotelOrderPaydetail.setOrdertype(1l);
                hotelOrderPaydetail.setAmount2(new BigDecimal(0));
            }
            hotelOrderPaydetail.setHousePrice(hotelOrderVo.TotalPrice);
            hotelOrderPaydetail.setOrderid(Long.valueOf(hotelOrder.getOrderNum()));
            hotelOrderPaydetail.setTradeorderid("0");
            hotelOrderPaydetail.setPaystatus(1l);
            hotelOrderPaydetail.setIsonline("onLine");
            hotelOrderPaydetail.setIsconfirm("1");
            hotelOrderPaydetailMapper.insertHotelOrderPaydetail(hotelOrderPaydetail);
        }


        if (insertHotelOrder <= 0){
            throw new Exception("创建订单失败" + hotelOrder.getOrderid());
        }
        if (hotelOrderVo.NumberOfRooms != null) {
            for (int i = 0; i < hotelOrderVo.NumberOfRooms.intValue(); i++) {
                StringBuilder sb = null;
                for (OrderRoom orderRoom : hotelOrderVo.orderRooms) {
                    for (CustomerVo customerVo : orderRoom.Customers) {
                        Name name = new Name();
                        name.setGuestName(customerVo.Name);
                        try {
                            ElongUtils.queryByIdGuestName(name);
                        } catch (Exception e){
                            throw new Exception(e.getMessage());
                        }

                        if (sb == null) {
                            sb = new StringBuilder();
                        } else {
                            sb.append(",");
                        }
                        sb.append(customerVo.Name);
                    }
                }

                for (Guest guest : condition.Customers) {
                    HotelOrderRoom hotelOrderRoom = new HotelOrderRoom();

                    if (hotelDetailOutput != null) {
                        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                            if (hotel.getRooms() != null && hotel.getRooms().size() > 0) {
                                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                                        if (ratePlan.getRoomTypeId().equals(condition.RoomTypeId)) {
                                            hotelOrderRoom.setRoomTypeName(room.getName());
                                        }
                                    }
                                }
                            } else {
                                throw new Exception("未查到该酒店房型信息" + hotelOrder.getOrderid());
                            }
                            if (hotel.getValueAdds() != null && hotel.getValueAdds().size() > 0) {
                                for (HotelDetailResponse.HotelsBean.ValueAdd valueAdd : hotel.getValueAdds()) {
                                    if (valueAdd.getAmount() > 0) {
                                        hotelOrderRoom.setBreakfastdesc(String.valueOf(valueAdd.getAmount()));
                                    } else {
                                        hotelOrderRoom.setBreakfastdesc("0");
                                    }
                                }
                            }
                        }
                    } else {
                        hotelOrderRoom.setRoomTypeName(condition.roomTypeName);
                        hotelOrderRoom.setBreakfastdesc(String.valueOf(condition.breakfast));
                    }


                    hotelOrderRoom.setRoomid(snowFlake.nextId());
                    hotelOrderRoom.setGuestname(guest.name);
                    hotelOrderRoom.setCreateTime(format.parse(dateNew));
                    hotelOrderRoom.setGuestname(sb.toString());
                    hotelOrderRoom.setRoomtypeid(hotelOrderVo.RoomTypeId);
                    hotelOrderRoom.setOrderid(Long.valueOf(hotelOrder.getOrderNum()));
                    hotelOrderRoom.setStarttime(format.parse(hotelOrderVo.ArrivalDate));
                    hotelOrderRoom.setEndtime(format.parse(hotelOrderVo.DepartureDate));
                    hotelOrderRoom.setPriceunit(hotelOrderVo.TotalPrice.divide(new BigDecimal(hotelOrderVo.NumberOfRooms)));
                    hotelOrderRoom.setPricetotal(hotelOrderVo.TotalPrice);
                    hotelOrderRoom.setCommunit(hotelOrderRoom.getPriceunit().divide(new BigDecimal(10)));
                    hotelOrderRoom.setCommtotal(hotelOrderVo.TotalPrice.divide(new BigDecimal(10)));
                    hotelOrderRoom.setActualcommtotal(hotelOrderRoom.getCommtotal());
                    hotelOrderRoom.setActualpricetotal(hotelOrderRoom.getPricetotal());
                    hotelOrderRoom.setCurrencyid(1L);
                    int orderRoom = hotelOrderRoomMapper.insertHotelOrderRoom(hotelOrderRoom);
                    //发票
                    if (condition.IsNeedInvoice){
                        HotelOrderInvoice hotelOrderInvoice = new HotelOrderInvoice();
                        hotelOrderInvoice.setCustomerid(customerId);
                        hotelOrderInvoice.setHotelid(Long.valueOf(condition.HotelId));

                        HotelOrder num = hotelOrderMapper.selectHotelOrderByOrderNum(orderNum.toString());
                        hotelOrderInvoice.setOrderid(num.getOrderid());
                        hotelOrderInvoice.setInvoicetitle(condition.billVo.invoiceTitle);
                        hotelOrderInvoice.setCompanyregisteraddress(condition.billVo.companyRegisterAddress);
                        hotelOrderInvoice.setCompanyregistertell(condition.billVo.companyRegisterTell);
                        hotelOrderInvoice.setDepositbank(condition.billVo.depositBank);
                        hotelOrderInvoice.setAccount(condition.billVo.account);
                        hotelOrderInvoice.setExpresstype(condition.billVo.expressType);
                        hotelOrderInvoice.setUsername(condition.billVo.userName);
                        hotelOrderInvoice.setPhone(condition.billVo.phone);
                        hotelOrderInvoice.setProvincename(condition.billVo.provinceName);
                        hotelOrderInvoice.setCityname(condition.billVo.cityName);
                        hotelOrderInvoice.setCountyname(condition.billVo.countyName);
                        hotelOrderInvoice.setAddress(condition.billVo.address);
                        hotelOrderInvoice.setInvoiceamont(condition.billVo.invoiceAmont);
                        hotelOrderInvoice.setInvoiceoption(condition.billVo.invoiceOption);
                        hotelOrderInvoice.setOrderNum(orderNum.toString());
                        hotelOrderInvoice.setInvoiceitin(condition.billVo.invoiceitin);
                        hotelOrderInvoice.setInvoicetype(condition.billVo.invoicetype);
                        hotelOrderInvoice.seteMail(condition.billVo.eMail);
                        hotelOrderInvoice.setCreatetime(dateNew);
                        int invoice = hotelOrderInvoiceMapper.insertHotelOrderInvoice(hotelOrderInvoice);
                        if (invoice <= 0){
                            throw new Exception("发票信息添加失败" + hotelOrder.getOrderid());
                        }
                    }

                    if (orderRoom <= 0){
                        throw new Exception("订单明细创建失败" + hotelOrder.getOrderid());
                    }
                }
                if (hotelOrderVo.productamount != null && hotelOrderVo.productamount.size() > 0){
                    //根据数量添加辅营产品
                    for (AssistProductVoApi assistProductVoApi : hotelOrderVo.productamount) {
                        HotelOrderAssist hotelOrderAssist = new HotelOrderAssist();
                        hotelOrderAssist.setAssistProductId(assistProductVoApi.getId());
                        hotelOrderAssist.setCreateTime(DateUtils.getNowDate());
                        hotelOrderAssist.setName(assistProductVoApi.getName());
                        hotelOrderAssist.setOrderId(hotelOrder.getOrderid());
                        hotelOrderAssist.setPrice(assistProductVoApi.getSalePrice());
                        hotelOrderAssist.setStatus(CustomerConstants.normal.getValue());
                        hotelOrderAssist.setProductCount(assistProductVoApi.getProductCount());
                        hotelOrderAssistMapper.insertHotelOrderAssist(hotelOrderAssist);
                    }
                }
            }
        }
        if (hotelOrderVo.productId != null){
            for (Integer integer : hotelOrderVo.productId) {
                if (hotelOrderVo.productamount!=null)
                {
                    AssistProductVoApi assistProductVoApi = hotelOrderVo.productamount.stream().filter(item->item.getId().equals(integer)).findFirst().orElse(null);
                    if (assistProductVoApi!=null)
                    {
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", assistProductVoApi.getStatus());
                        map.put("businessType", assistProductVoApi.getBusinessType());
                        map.put("id", integer);
                        AssistProductVoApi assistProductVo = remoteCustomerService.assistProduct(map);
                        HotelOrderAssist hotelOrderAssist = new HotelOrderAssist();
                        hotelOrderAssist.setName(assistProductVo.getName());
                        hotelOrderAssist.setPrice(assistProductVo.getSalePrice());
                        hotelOrderAssist.setAssistProductId(assistProductVo.getId());
                        hotelOrderAssist.setStatus("normal");
                        hotelOrderAssist.setOrderId(hotelOrder.getOrderid());
                        hotelOrderAssistMapper.insertHotelOrderAssist(hotelOrderAssist);
                    }
                }
            }
        }

        redisService.setCacheObject(HOTEL + customer.getData().getCustomerId() + ORDER + hotelOrder.getOrderNum(), JSON.toJSON(hotelOrder), 60 * 3000L, TimeUnit.SECONDS);

        hotelIdNumVo.setHotelOrderNum(hotelOrder.getOrderNum());
//        HotelOrder orderId = hotelOrderMapper.selectHotelOrderByOrderNum(hotelOrderVo.AffiliateConfirmationId);
        hotelIdNumVo.setHotelOrderId(String.valueOf(hotelOrder.getOrderid()));

        String messageContent = "您在" + newDate + "日，预定" + condition.HotelName + "，请在规定时间内支付，以免影响您的日程";
        Map<String,String> map = new HashMap<>();
        map.put("customerId", customer.getData().getCustomerId().toString());
        map.put("messageContent", messageContent);
        map.put("businessType", BusinessTypeConstants.hotel.getValue());
        map.put("businessOrderId", orderNum.toString());
        remoteCustomerService.addCustomerMessage(map);

        return hotelIdNumVo;
    }

    /**
     * 酒店创建订单（艳东版）
     * */
    @Override
    public HotelIdNumVo hotelSelOrder(String token, CreateOrderVo condition, Long customerId) throws Exception {
        HotelIdNumVo hotelIdNumVo = new HotelIdNumVo();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        Date date = new Date();
        String dateNew = format.format(date);
        String newDate = dateFormat.format(date);

        CalculationDTO calculationDTO = null;

        CalculationVOApi calculationVOApi = new CalculationVOApi();
        List<BigDecimal> prices = new ArrayList<>();
        prices.add(condition.TotalPrice);
        calculationVOApi.setPrices(prices);//商品单价集合
        calculationVOApi.setAmount(condition.NumberOfCustomers);//商品数量
        List<BigDecimal> additionalPrices = new ArrayList<>();
        if (condition.productamount != null){
            additionalPrices.add(condition.productamount.getSalePrice());
        }
        calculationVOApi.setAdditionalPrices(additionalPrices);//附加商品单价集合
        if (additionalPrices != null && additionalPrices.size() > 0){
            calculationVOApi.setAdditionalAmount(condition.NumberOfCustomers);//附加商品数量
        }
        else {
            calculationVOApi.setAdditionalAmount(0);//附加商品数量
        }
        calculationVOApi.setCouponId(0l);//优惠卷id
        calculationVOApi.setDepositAmount(condition.amount);//用户拥有的金币数量
        calculationVOApi.setUseDeposit(condition.useDeposit);//是否使用金币
        //用户拥有的积分数量
        if (condition.points==null)
        {
            calculationVOApi.setPointAmount(0);
        }else {
            calculationVOApi.setPointAmount(Integer.valueOf(condition.points.toString()));
        }
        calculationVOApi.setUsePoint(false);//是否使用积分
        calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
        if (calculationDTO.getPrice().compareTo(condition.totalsalePrice) != 0){
            throw new Exception("支付金额发生变化");
        }

        R<Customer> customer;
        if (customerId == null || customerId == 0){
            customer = remoteCustomerService.getLoginCustomerByToken(token);
        }
        else {
            customer = remoteCustomerService.getCustomerId(customerId);
        }

        if (customer.getData() == null){
            throw new Exception("会员信息未更新，请重新登录");
        }
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());

        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);

        HotelOrder hotelOrder = new HotelOrder();
        hotelOrder.setHotelstar(condition.hotelstar);
        SnowFlake snowFlake = new SnowFlake(30, 30);
        Long orderNum = snowFlake.nextId();
        condition.AffiliateConfirmationId = orderNum.toString();

        if (customerCardR.equals("") || customerCardR == null){
            throw new Exception("该会员没有可使用的银行卡");
        }

        try {
            hotelOrder.setOrdertype(condition.orderType);
            hotelOrder.setHoteladdress(condition.address);
            hotelOrder.setHotelphone(condition.phone);
            hotelOrder.setHotelstar(condition.hotelstar);
//            hotelOrder.setHotelcode(ratePlan.getHotelCode());

            if (condition.AffiliateConfirmationId != null){
                hotelOrder.setOrderid(Long.valueOf(condition.AffiliateConfirmationId));
            }
            hotelOrder.setAgentid(0L);
            hotelOrder.setOpemployeeid(788L);
            hotelOrder.setOrdersourcetypeid(1L);
            hotelOrder.setHotelid(condition.HotelId);
            hotelOrder.setOrderversion("1");
            hotelOrder.setHotelname(condition.HotelName);
            hotelOrder.setRegionid(0L);
            hotelOrder.setPayAmount(condition.payAmount);
            hotelOrder.setOrderstatusid(HotelOrderStatus.Status.TOBECONFIRMED.getCode());
            hotelOrder.setOrderflowstatusid(HotelOrderStatus.FlowStatus.TOBEPAID.getCode());
            hotelOrder.setCustomerid(customer.getData().getCustomerId());

            CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
            customerIdVoApi.setCustomerId(customer.getData().getCustomerId());
            customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);
            if (calculationVOApi != null){
                hotelOrder.setCustomercardid(customerIdVoApi.getCustomerCard());
            }

            hotelOrder.setArrivetime(condition.ArrivalDate);
            hotelOrder.setCheckouttime(condition.DepartureDate);
            hotelOrder.setCreateTime(new Date());
            hotelOrder.setOrderoccupttypeid(1L);
            for (Guest contact : condition.Customers) {
                hotelOrder.setEmployeename(contact.name);
                break;
            }
            hotelOrder.setCustomername(customer.getData().getCustomerName());
            hotelOrder.setIsdelete("false");
            hotelOrder.setPhone(condition.Mobile);
            hotelOrder.setNumberOfRooms(condition.NumberOfRooms);
            if (condition.points != null) {
                hotelOrder.setPoints(new BigDecimal(condition.points));
            }else
            {
                hotelOrder.setPoints(new BigDecimal(0));
            }
            if (condition.couponId != null && condition.couponId != 0) {
                hotelOrder.setCouponID(condition.couponId);
                R<Coupon> coupon = remoteCustomerService.couponById(condition.couponId);
                if (coupon.getData().getCouponType().equals("CouponTypeFullMinus") || coupon.getData().getCouponType().equals("CouponTypeCashCoupon")) {
                    hotelOrder.setCouponAmount(coupon.getData().getCouponPrice());
                } else {
                    BigDecimal price = coupon.getData().getCouponDiscount();
                    BigDecimal divide = price.divide(new BigDecimal(100));
                    BigDecimal countPrice = condition.totalsalePrice.multiply(divide);
                    BigDecimal couponAmount = condition.totalsalePrice.subtract(countPrice);
                    hotelOrder.setCouponAmount(couponAmount);
                }
            }
            if (condition.usedDeposit != null) {
                hotelOrder.setDepositAmount(condition.usedDeposit);
            }

            hotelOrder.setOpemployeeid(1l);

            if (condition.sourceTypeName != null && !condition.sourceTypeName.equals("")){
                hotelOrder.setSourceWay(condition.sourceTypeName);
            }
            else {
                throw new Exception("订单渠道不能为空");
            }

            hotelOrder.setPlusmoneystatus(CustomerConstants.waitPay.getValue());
            hotelOrder.setHotelid(condition.HotelId);
            hotelOrder.setOrderversion("1");
            hotelOrder.setHotelname(condition.HotelName);
            hotelOrder.setHoteladdress(condition.address);
            hotelOrder.setHotelphone(condition.phone);

            DicProvince dicProvince = dicProvinceMapper.selectDicProvinceByProvinceName(condition.cityName + "%");

            hotelOrder.setCityid(dicProvince.getId().toString());
            hotelOrder.setOrderstatusid(1l);
            hotelOrder.setOrderflowstatusid(1l);

//            List<HotelSupplierLink> hotelSupplierLinks = hotelSupplierLinkMapper.selectHotelSupplierLinkByHotelId(condition.HotelId);
//            HotelSupplierLink hotelSupplierLink;
//            if (hotelSupplierLinks.size() > 1){
//                for (HotelSupplierLink supplierLink : hotelSupplierLinks) {
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(supplierLink.getCreateTime());
//                    supplierLink.setMillisecond(calendar.getTimeInMillis());
//                }
//                hotelSupplierLinks.sort((y, x) -> Double.compare(y.getMillisecond(), x.getMillisecond()));
//            }
//            hotelSupplierLink = hotelSupplierLinks.get(0);
            if (condition.hotelEnum != null && !condition.hotelEnum.equals("")){
                hotelOrder.setSupplierid(condition.hotelEnum);
            }
            else {
                throw new Exception("酒店供应商枚举不能为空，枚举参数由酒店列表返回");
            }
            hotelOrder.setCustomerid(customer.getData().getCustomerId());

            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customer.getData().getCustomerId());

            CustomerCard customerCard = remoteCustomerService.customerCardList(map);

            hotelOrder.setCardtypeid(customerCard.getCardId());
            hotelOrder.setCustomercardid(customerCard.getCardCode());
            hotelOrder.setArrivetime(condition.ArrivalDate);
            hotelOrder.setCheckouttime(condition.DepartureDate);
            //预付
            if (condition.PaymentType.equals(HotelEnum.RegionalLocation.Prepay.getValue())){
                hotelOrder.setOrdertype(3l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待支付.getValue());
            }
            //现付
            else if (condition.PaymentType.equals(HotelEnum.RegionalLocation.SelfPay.getValue())){
                hotelOrder.setOrdertype(1l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待核实入住.getValue());
            }
            //担保
            else if (condition.PaymentType.equals(HotelEnum.RegionalLocation.Guarantee.getValue())){
                hotelOrder.setOrdertype(2l);
                hotelOrder.setShowstatus(HotelEnum.RegionalLocation.ElongOrderType.等待担保.getValue());
            }
            else {
                throw new Exception("支付类型错误");
            }
            hotelOrder.setCustomername(customer.getData().getCustomerName());
            hotelOrder.setIsdelete("false");

            hotelOrder.setCreateTime(dateFormat.parse(newDate));

            hotelOrder.setNumberOfRooms(condition.NumberOfRooms);
            // todo 测试金额写死
            String pay = "0.1";
            hotelOrder.setPayAmount(new BigDecimal(pay));
//            hotelOrder.setPayAmount(hotelOrderVo.totalsalePrice);

            Calendar arrivalDate = Calendar.getInstance();
            Calendar departureDate = Calendar.getInstance();
            arrivalDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(condition.ArrivalDate));
            departureDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(condition.DepartureDate));
            long i = departureDate.getTimeInMillis() - arrivalDate.getTimeInMillis();
            i = i / 1000 / 60 / 60 / 24;
            if (i <= 0){
                i = 1;
            }
            hotelOrder.setCheckInTime(i);
            hotelOrder.setLatestArrivalTime(condition.LatestArrivalTime);
            hotelOrder.setEarliestArrivalTime(condition.EarliestArrivalTime);
            hotelOrder.setPhone(condition.Mobile);
            hotelOrder.setRatePlanId(condition.RatePlanId.toString());
            hotelOrder.setOrderNum(orderNum.toString());
            if (token != null) {
                hotelOrder.setSourceWay("App");
            } else {
                hotelOrder.setSourceWay("Crm");
            }
            if (hotelOrder.geteLongOrdertype() != null){
                switch (hotelOrder.geteLongOrdertype()){
                    case "Prepay":
                        hotelOrder.setOrdertype(3l);
                        break;
                    case "SelfPay":
                        hotelOrder.setOrdertype(1l);
                        break;
                }
            }
            else if (condition.bankCardNum != null && !condition.bankCardNum.equals("")){
                hotelOrder.setOrdertype(2l);
                hotelOrder.setBackCardNum(condition.bankCardNum);
            }
            // todo 测试专用
            hotelOrder.setOrdertype(3l);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        int insertHotelOrder = hotelOrderMapper.insertHotelOrder(hotelOrder);


        //新增支付信息
        HotelOrderPaydetail hotelOrderPaydetail = new HotelOrderPaydetail();
        if (condition.PaymentType.equals("Prepay")){
            hotelOrderPaydetail.setRemittanceprice(condition.TotalPrice.multiply(new BigDecimal(condition.NumberOfCustomers)));
            for (DiscountDescDTOApi item : calculationDTO.getActualPriceDetailed().getDiscountDesc()) {

                if (item.getDesc().equals("优惠券")) {
                    if (condition.usePoint) {
                        hotelOrderPaydetail.setPaymoney(item.getPrice());
                    }
                    else {
                        hotelOrderPaydetail.setPaymoney(new BigDecimal(0));
                    }
                }
                if (item.getDesc().equals("金币")) {
                    if (condition.useDeposit){
                        hotelOrderPaydetail.setDepositmoney(item.getPrice());
                    }
                    else {
                        hotelOrderPaydetail.setDepositmoney(new BigDecimal(0));
                    }
                }
            }

            if (condition.productamount != null){
                hotelOrderPaydetail.setAmount(condition.productamount.getSalePrice());
            }
            else {
                hotelOrderPaydetail.setAmount(new BigDecimal(0));
            }
            hotelOrderPaydetail.setOrdertype(2l);
            hotelOrderPaydetail.setAmount2(calculationDTO.getPrice());
        }
        else {
            hotelOrderPaydetail.setRemittanceprice(new BigDecimal(0));
            hotelOrderPaydetail.setPaymoney(new BigDecimal(0));
            hotelOrderPaydetail.setDepositmoney(new BigDecimal(0));
            hotelOrderPaydetail.setAmount(new BigDecimal(0));
            hotelOrderPaydetail.setOrdertype(1l);
            hotelOrderPaydetail.setAmount2(new BigDecimal(0));
        }
        hotelOrderPaydetail.setHousePrice(condition.TotalPrice);
        hotelOrderPaydetail.setOrderid(Long.valueOf(hotelOrder.getOrderNum()));
        hotelOrderPaydetail.setTradeorderid("0");
        hotelOrderPaydetail.setPaystatus(1l);
        hotelOrderPaydetail.setIsonline("onLine");
        hotelOrderPaydetail.setIsconfirm("1");
        hotelOrderPaydetailMapper.insertHotelOrderPaydetail(hotelOrderPaydetail);

        if (insertHotelOrder <= 0){
            Long employeeId;
            if (customerId == 0){
                Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
                if (employee != null){
                    throw new Exception("登录已过期");
                }
                employeeId =  employee.getEmployeeId();
            }
            else {
                employeeId = 10l;
            }

            String person = null;
            if (condition.Customers != null && condition.Customers.size() > 0){
                for (int i = 0; i < condition.Customers.size(); i++) {
                    if (i == 0){
                        person = condition.Customers.get(0).name;
                    }
                    else {
                        person = person + "|" + condition.Customers.get(0).name;
                    }
                }
            }

            hotelOrderException(person, customerId,  condition.Mobile, condition.HotelName, "创建订单失败", condition.hotelType, "0", employeeId);

            throw new Exception("创建订单失败");
        }
        if (condition.NumberOfRooms != null) {
            for (int i = 0; i < condition.NumberOfRooms.intValue(); i++) {
                StringBuilder sb = null;
                for (Guest guest : condition.Customers) {
                    Name name = new Name();
                    name.setGuestName(guest.name);
                    try {
                        ElongUtils.queryByIdGuestName(name);
                    } catch (Exception e){
                        throw new Exception(e.getMessage());
                    }

                    if (sb == null) {
                        sb = new StringBuilder();
                    } else {
                        sb.append(",");
                    }
                    sb.append(guest.name);
                }

                Long orderRoomId = snowFlake.nextId();

                for (Guest guest : condition.Customers) {
                    HotelOrderRoom hotelOrderRoom = new HotelOrderRoom();
                    hotelOrderRoom.setRoomTypeName(condition.roomTypeName);
                    hotelOrderRoom.setBreakfastdesc(condition.valueAdds);
                    hotelOrderRoom.setRoomid(orderRoomId);
                    hotelOrderRoom.setGuestname(guest.name);
                    hotelOrderRoom.setCreateTime(format.parse(dateNew));
                    hotelOrderRoom.setGuestname(sb.toString());
                    hotelOrderRoom.setRoomtypeid(condition.RoomTypeId);
                    hotelOrderRoom.setOrderid(Long.valueOf(hotelOrder.getOrderNum()));
                    hotelOrderRoom.setStarttime(dateFormat.parse(condition.ArrivalDate));
                    hotelOrderRoom.setEndtime(dateFormat.parse(condition.DepartureDate));
                    hotelOrderRoom.setPriceunit(condition.TotalPrice.divide(new BigDecimal(condition.NumberOfRooms)));
                    hotelOrderRoom.setPricetotal(condition.TotalPrice);
                    hotelOrderRoom.setCommunit(hotelOrderRoom.getPriceunit().divide(new BigDecimal(10)));
                    hotelOrderRoom.setCommtotal(condition.TotalPrice.divide(new BigDecimal(10)));
                    hotelOrderRoom.setActualcommtotal(hotelOrderRoom.getCommtotal());
                    hotelOrderRoom.setActualpricetotal(hotelOrderRoom.getPricetotal());
                    hotelOrderRoom.setCurrencyid(1L);
                    int orderRoom = hotelOrderRoomMapper.insertHotelOrderRoom(hotelOrderRoom);

                    //发票
                    if (condition.IsNeedInvoice){
                        HotelOrderInvoice hotelOrderInvoice = new HotelOrderInvoice();
                        hotelOrderInvoice.setCustomerid(customerId);
                        hotelOrderInvoice.setHotelid(Long.valueOf(condition.HotelId));

                        HotelOrder num = hotelOrderMapper.selectHotelOrderByOrderNum(orderNum.toString());
                        hotelOrderInvoice.setOrderid(num.getOrderid());
                        hotelOrderInvoice.setInvoicetitle(condition.billVo.invoiceTitle);
                        hotelOrderInvoice.setCompanyregisteraddress(condition.billVo.companyRegisterAddress);
                        hotelOrderInvoice.setCompanyregistertell(condition.billVo.companyRegisterTell);
                        hotelOrderInvoice.setDepositbank(condition.billVo.depositBank);
                        hotelOrderInvoice.setAccount(condition.billVo.account);
                        hotelOrderInvoice.setExpresstype(condition.billVo.expressType);
                        hotelOrderInvoice.setUsername(condition.billVo.userName);
                        hotelOrderInvoice.setPhone(condition.billVo.phone);
                        hotelOrderInvoice.setProvincename(condition.billVo.provinceName);
                        hotelOrderInvoice.setCityname(condition.billVo.cityName);
                        hotelOrderInvoice.setCountyname(condition.billVo.countyName);
                        hotelOrderInvoice.setAddress(condition.billVo.address);
                        hotelOrderInvoice.setInvoiceamont(condition.billVo.invoiceAmont);
                        hotelOrderInvoice.setInvoiceoption(condition.billVo.invoiceOption);
                        hotelOrderInvoice.setOrderNum(orderNum.toString());
                        hotelOrderInvoice.setInvoiceitin(condition.billVo.invoiceitin);
                        hotelOrderInvoice.setInvoicetype(condition.billVo.invoicetype);
                        hotelOrderInvoice.seteMail(condition.billVo.eMail);
                        hotelOrderInvoice.setCreatetime(dateNew);
                        int invoice = hotelOrderInvoiceMapper.insertHotelOrderInvoice(hotelOrderInvoice);
                        if (invoice <= 0){
                            throw new Exception("发票信息添加失败");
                        }
                    }

                    if (orderRoom <= 0){
                        throw new Exception("订单明细创建失败");
                    }
                }
            }
        }
        if (condition.productId != null){
            for (Integer integer : condition.productId) {
                Map<String, Object> map = new HashMap<>();
                map.put("status", AssistProductEnum.activation.getValue());
                map.put("businessType", AssistProductEnum.hotel.getValue());
                map.put("id", integer);
                AssistProductVoApi assistProductVo = remoteCustomerService.assistProduct(map);

                HotelOrderAssist hotelOrderAssist = new HotelOrderAssist();
                hotelOrderAssist.setName(assistProductVo.getName());
                hotelOrderAssist.setPrice(assistProductVo.getSalePrice());
                hotelOrderAssist.setAssistProductId(assistProductVo.getId());
                hotelOrderAssist.setStatus("normal");
                hotelOrderAssist.setOrderId(hotelOrder.getOrderid());
                hotelOrderAssistMapper.insertHotelOrderAssist(hotelOrderAssist);
            }
        }

        redisService.setCacheObject(HOTEL + customer.getData().getCustomerId() + ORDER + hotelOrder.getOrderNum(), JSON.toJSON(hotelOrder), 60 * 3000L, TimeUnit.SECONDS);

        hotelIdNumVo.setHotelOrderNum(hotelOrder.getOrderNum());
//        HotelOrder orderId = hotelOrderMapper.selectHotelOrderByOrderNum(hotelOrderVo.AffiliateConfirmationId);
        hotelIdNumVo.setHotelOrderId(String.valueOf(hotelOrder.getOrderid()));

        String messageContent = "您在" + newDate + "日，预定" + condition.HotelName + "，请在规定时间内支付，以免影响您的日程";
        Map<String,String> map = new HashMap<>();
        map.put("customerId", customer.getData().getCustomerId().toString());
        map.put("messageContent", messageContent);
        map.put("businessType", BusinessTypeConstants.hotel.getValue());
        map.put("businessOrderId", orderNum.toString());
        remoteCustomerService.addCustomerMessage(map);
        return hotelIdNumVo;
    }

    /**
     * 酒店价格查询
     * */
    @Override
    public BigDecimal hotelPrice(HotelDetailInput input) throws Exception {
        if (input.HotelIds != null && !input.HotelIds.equals("") &&
                input.ArrivalDate != null && !input.ArrivalDate.equals("") &&
                input.DepartureDate != null && !input.DepartureDate.equals("") &&
                input.RoomTypeId != null && !input.RoomTypeId.equals("")){
            BigDecimal price = new BigDecimal(0);
            HotelDetailOutput hotelDetailOutput;
            try {
                hotelDetailOutput = ElongUtils.queryByIdHotel(input);
                if (hotelDetailOutput.Code.equals("0")){
                    for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                        for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                                if (ratePlan.getRoomTypeId().equals(input.RoomTypeId)){
                                    price = ratePlan.getTotalRate();
                                    break;
                                }
                            }
                            if (price.compareTo(new BigDecimal(0)) == 1){
                                break;
                            }
                        }
                        if (price.compareTo(new BigDecimal(0)) == 1){
                            break;
                        }
                    }
                    return price;
                }
                else {
                    throw new Exception("未查到数据");
                }
            } catch (Exception e){
                throw new Exception(e.getMessage());
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 酒店取消政策
     * */
    @Override
    public CancellationPolicy cancellationPolicy(HotelDetailInput input) throws Exception {
        CancellationPolicy cancellationPolicy = new CancellationPolicy();
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (hotelDetailOutput.Code.equals("0")){
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                        //参数（input.RoomTypeId）与查询结果销售房型编号对应，确定对应的预付规则编号
                        if (ratePlan.getRoomTypeId().equals(input.RoomTypeId)){
                            for (HotelDetailResponse.HotelsBean.PrepayRulesBean prepayRule : hotel.getPrepayRules()) {
                                //通过以确定的对应的预付规则编号，获取预付规则
                                if (ratePlan.getPrepayRuleIds().equals(String.valueOf(prepayRule.getPrepayRuleId()))){
                                    cancellationPolicy.setDescription(prepayRule.getDescription());
                                    return cancellationPolicy;
                                }
                            }
                        }
                    }
                }
            }
        }
        else {
            throw new Exception("未查到数据");
        }
        return null;
    }

    /**
     * 特惠酒店
     * */
    @Override
    public List<SpecialHotelVo> specialHotel(SpecialHotel specialHotel) throws Exception {
        List<SpecialHotelVo> specialHotelVoList = new ArrayList<>();
        ConditionVo conditionVo = new ConditionVo();
        HotelDetailInput input = new HotelDetailInput();

        conditionVo.setArrivalDate(specialHotel.getArrivalDate());
        conditionVo.setDepartureDate(specialHotel.getDepartureDate());
        conditionVo.setCityName(specialHotel.getCityName());
        conditionVo.setPageIndex(specialHotel.getPageIndex());
        conditionVo.setPageSize(specialHotel.getPageSize());

        input.ArrivalDate = specialHotel.getArrivalDate();
        input.DepartureDate = specialHotel.getDepartureDate();

        HotelDetailOutput hotelDetailOutput;
        hotelDetailOutput = queryByIdHotelList(conditionVo);
        if (hotelDetailOutput== null)
        {
            throw new Exception("城市信息为空！");
        }

        if (hotelDetailOutput.Code.equals("0")){
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                        //判断是否为特惠酒店
                        if (ratePlan.isLastMinuteSale() == true){
                            SpecialHotelVo specialHotelVo = new SpecialHotelVo();
                            for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                                specialHotelVo.setHotelName(detailBean.getHotelName());
                                specialHotelVo.setAddress(detailBean.getAddress());
                                specialHotelVo.setThumbNailUrl(detailBean.getThumbNailUrl());
                            }

                            HotelVo hotelVo = hotelMapper.selectHotelVoByHotelCode(hotel.getHotelId());
                            specialHotelVo.setCommentScore(hotelVo.getCommentScore().doubleValue());

                            specialHotelVo.setTotalRate(ratePlan.getTotalRate());
                            specialHotelVo.setStartTime(ratePlan.getStartTime());
                            specialHotelVo.setEndTime(ratePlan.getEndTime());

                            input.HotelIds = hotel.getHotelId();
                            input.RoomTypeId = ratePlan.getRoomTypeId();
                            HotelDetailOutput hotelDetail = ElongUtils.queryByIdHotel(input);
                            if (hotelDetail.Code.equals("0")){
                                for (HotelDetailResponse.HotelsBean resultHotel : hotelDetail.Result.getHotels()) {
                                    for (HotelDetailResponse.HotelsBean.RoomsBean resultHotelRoom : resultHotel.getRooms()) {
                                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean plan : resultHotelRoom.getRatePlans()) {
                                            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.NightlyRatesBean nightlyRate : plan.getNightlyRates()) {
                                                specialHotelVo.setBasis(nightlyRate.getBasis());
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                throw new Exception("未查到酒店原价信息");
                            }
                            specialHotelVoList.add(specialHotelVo);
                        }
                    }
                }
            }
        }
        else {
            throw new Exception("未查到酒店列表信息");
        }

        return specialHotelVoList;
    }

    /**
     * 酒店房型筛选（查询）
     * */
    @Override
    public HotelDetails hotelRoomScreening(RoomTypeVo roomTypeVo) throws Exception {
        HotelDetailInput input = new HotelDetailInput();
        input.ArrivalDate = roomTypeVo.getArrivalDate();
        input.DepartureDate = roomTypeVo.getDepartureDate();
        input.HotelIds = roomTypeVo.getHotelId();
        //支付：（在线付/到店付）单选
        if (roomTypeVo.getPay() != null && !roomTypeVo.getPay().equals("")){
            if (roomTypeVo.getPay().equals(HotelEnum.RegionalLocation.PayOnline.getValue())){//在线付
                input.PaymentType = "Prepay";
            }
            else if (roomTypeVo.getPay().equals(HotelEnum.RegionalLocation.PayAtTheStore.getValue())){//到店付
                input.PaymentType = "SelfPay";
            }
        }
        HotelDetailOutput hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        if (hotelDetailOutput.Code.equals("0")){
            HotelDetails filter = filter(roomTypeVo, hotelDetailOutput);
            if (filter != null){
                return filter;
            }
            else {
                throw new Exception("筛选失败");
            }
        }
        else {
            throw new Exception("未查到酒店详细信息");
        }
    }

    /**
     * 热门酒店
     * */
    @Override
    public List<PopularHotel> hotelPopular() throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(new Date());
        date = date + " 23:59:59";

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -2);
        Date startData = c.getTime();
        String backDate = format.format(startData);
        backDate = backDate + " 23:59:59";

        List<HotelOrder> hotelOrderList = hotelOrderMapper.selectHotelOrderPopularList(date, backDate);
        List<HotelOrder> hotelOrders = new ArrayList<>();
        if (hotelOrderList != null){
            for (HotelOrder hotelOrder : hotelOrderList) {
                int num = hotelOrderMapper.selectHotelOrderPopularNum(date, backDate, hotelOrder.getHotelid());
                hotelOrder.setNum(num);
                hotelOrders.add(hotelOrder);
            }

            hotelOrders.sort((y, x) -> Double.compare(y.getNum(), x.getNum()));

            List<String> idList = new ArrayList<>();
            for (int i = 0 ; i < hotelOrders.size() ; i++){
                if (idList.size() < 3){
                    idList.add(hotelOrders.get(i).getHotelid());
                }
                else {
                    break;
                }
            }

            List<PopularHotel> popularHotelList = new ArrayList<>();
            for (String id : idList) {
                HotelDetailInput input = new HotelDetailInput();
                Date time = new Date();
                input.ArrivalDate = format.format(time);

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(time);
                calendar.add(Calendar.DATE, 1);
                input.DepartureDate = format.format(calendar.getTime());

                input.HotelIds = id;

                HotelDetailOutput hotelDetailOutput;
                try {
                    hotelDetailOutput = ElongUtils.queryByIdHotel(input);
                } catch (Exception e){
                    throw new Exception(e.getMessage());
                }

                PopularHotel popularHotel = new PopularHotel();
                popularHotel.setComment("房间很温馨");

                if (hotelDetailOutput.Result.getHotels() == null){
                    throw new Exception("未查询到信息");
                }
                for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                    popularHotel.setBaseMinPrice(new BigDecimal(hotel.getLowRate()));

                    List<HotelSupplierLink> hotelSupplierLinks = hotelSupplierLinkMapper.selectHotelSupplierLinkByHotelCode(hotel.getHotelId());

                    long hotelId = 0;
                    HotelSupplierLink hotelLink = null;
                    if (hotelSupplierLinks.size() > 1){
                        for (int i = 0 ; i < hotelSupplierLinks.size() ; i++) {
                            if (i == 0){//首次循环赋值
                                hotelLink = hotelSupplierLinks.get(i);
                            }
                            else {
                                Date dateTime = hotelSupplierLinks.get(i).getCreateTime();

                                if (hotelLink.getCreateTime().compareTo(dateTime) > 0) {//比较两个时间，保留距离当前时间最近的酒店id
                                    hotelLink = hotelSupplierLinks.get(i);
                                }
                            }
                        }
                        hotelId = hotelLink.getHotelId();
                    }
                    else {
                        for (HotelSupplierLink hotelSupplierLink : hotelSupplierLinks) {
                            hotelId = hotelSupplierLink.getHotelId();
                        }
                    }
                    popularHotel.setHotelId(Long.parseLong(id));

                    DicReviews dicReviews = dicReviewsMapper.selectDicReviewsById(hotelId);
                    if (dicReviews != null && dicReviews.getReviewsName() != null){
                        String score = (dicReviews.getReviewsName() / 10) + "." + (dicReviews.getReviewsName() % 10);
                        popularHotel.setCommentScore(new BigDecimal(score));
                    }
                    else {
                        popularHotel.setCommentScore(new BigDecimal(4.0));
                    }

                    if (hotel.getDetail() == null){
                        throw new Exception("未查到酒店信息");
                    }
                    for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                        popularHotel.setHotelName(detailBean.getHotelName());
                        popularHotel.setPicPath(detailBean.getThumbNailUrl());
                        if (detailBean.getStarRate() != 0){
                            switch (detailBean.getStarRate()){
                                case 1:
                                    popularHotel.setStarName("一星级");
                                    break;
                                case 2:
                                    popularHotel.setStarName("二星级");
                                    break;
                                case 3:
                                    popularHotel.setStarName("三星级");
                                    break;
                                case 4:
                                    popularHotel.setStarName("四星级");
                                    break;
                                case 5:
                                    popularHotel.setStarName("五星级");
                                    break;
                            }
                        }
                        else {
                            switch (detailBean.getCategory()){
                                case 0:
                                case 1:
                                case 2:
                                    popularHotel.setStarName("客栈");
                                    break;
                                case 3:
                                    popularHotel.setStarName("舒适型");
                                    break;
                                case 4:
                                    popularHotel.setStarName("高档型");
                                    break;
                                case 5:
                                    popularHotel.setStarName("豪华型");
                                    break;
                            }
                        }
                    }
                }
                popularHotelList.add(popularHotel);
            }
            return popularHotelList;
        }
        else {
            return null;
        }
    }

    /**
     * 酒店取消订单（数据库）
     * */
    @Override
    public int updateHotelOrder(String token, Long orderId) throws Exception {
        R<Customer> loginCustomerByToken = remoteCustomerService.getLoginCustomerByToken(token);
        if (loginCustomerByToken.getData() != null){
            Long customerId = loginCustomerByToken.getData().getCustomerId();
            CancelVo cancelVo = new CancelVo();
            cancelVo.setCustomerId(customerId);
            cancelVo.setOrderId(orderId);
            int i = hotelOrderMapper.updateOrder(cancelVo);
            if (i > 0){
                return 1;
            }
            else {
                return 0;
            }
        }
        else {
            throw new Exception("登录已过期，请重新登录");
        }
    }

    /**
     * 后台酒店条件查询
     * */
    @Override
    public List<HotelVo> hotelsList(BackHotelVo backHotelVo) throws Exception {
        backHotelVo.setPages((backHotelVo.getPages() - 1) * backHotelVo.getArticles());

        List<HotelVo> hotelVos = hotelMapper.hotelsList(backHotelVo.getCity(), backHotelVo.getHotelName(),
                backHotelVo.getStar(), backHotelVo.getLevel(), backHotelVo.getPages(), backHotelVo.getArticles());
        if (hotelVos != null && hotelVos.size() > 0){
            List<HotelVo> hotelVoList = new ArrayList<>();
            for (HotelVo hotelVo : hotelVos) {
                HotelVo backHotel = new HotelVo();
                backHotel.setId(hotelVo.getId());
                backHotel.setHotelName(hotelVo.getHotelName());

                if (hotelVo.getStarId() != null && hotelVo.getStarId() != 0){
                    DicStars dicStars = dicStarsMapper.dicStarsByid(hotelVo.getStarId());
                    if (dicStars != null){
                        backHotel.setStarName(dicStars.getStarsName());
                    }
                    else {
                        throw new Exception("未查到星级信息，请更新数据库信息" + hotelVo.getStarId());
                    }
                }

                if (hotelVo.getRecommendLevel() != null && hotelVo.getRecommendLevel() != 0){
                    String recommendLevel = recommendLevel(hotelVo.getRecommendLevel());
                    backHotel.setRecommendLevelName(recommendLevel);
                }

                hotelVoList.add(backHotel);
            }
            return hotelVoList;
        }
        else {
            throw new Exception("没有符合条件的数据");
        }
    }

    /**
     * 根据拼音查询酒店名称
     * */
    @Override
    public List<HotelPinYinVo> selectHotelVoByPinYin(String pinYin, String cityName) throws Exception {
        if (pinYin != null && !pinYin.equals("")){
            List<HotelVo> hotelVos = hotelMapper.selectHotelVoByPinYin("%" + pinYin + "%", cityName);
            if (hotelVos != null && hotelVos.size() > 0){
                List<HotelPinYinVo> hotelPinYinVoList = new ArrayList<>();
                for (HotelVo hotelVo : hotelVos) {
                    HotelPinYinVo hotelPinYinVo = new HotelPinYinVo();
                    hotelPinYinVo.setHotelId(hotelVo.getId());
                    hotelPinYinVo.setHotelName(hotelVo.getHotelName());
                    hotelPinYinVoList.add(hotelPinYinVo);
                }
                return hotelPinYinVoList;
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 根据经纬度查询周边酒店
     * */
    @Override
    public List<ParameterHotelVo> selectHotelVoLngAndLat(String lng, String lat) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        if (lng != null && !lng.equals("") && lat != null && !lat.equals("")){
            //查询指定酒店附近2500米内的所有酒店信息，取前四个酒店输出信息
            double distance = 2500;
            Map<String, Double> around = latitudeUtil.getAround(new Double(lng), new Double(lat), distance);

            List<HotelVo> hotelVos = hotelMapper.selectHotelVoLngAndLat(around.get("minLng"), around.get("maxLng"), around.get("minLat"), around.get("maxLat"));

            if (hotelVos != null && hotelVos.size() > 0){
                List<ParameterHotelVo> parameterHotelVoList = new ArrayList<>();
                for (HotelVo hotelVo : hotelVos) {
                    ParameterHotelVo parameterHotelVo = new ParameterHotelVo();
                    parameterHotelVo.setId(hotelVo.getId());
                    parameterHotelVo.setHotelName(hotelVo.getHotelName());
                    parameterHotelVo.setPicPath(hotelVo.getPicPath());
                    parameterHotelVo.setCommentScore(hotelVo.getCommentScore());
                    parameterHotelVo.setCommentCount(hotelVo.getCommentCount());
                    parameterHotelVo.setAddress(hotelVo.getAddress());
                    parameterHotelVo.setBaseMinPrice(hotelVo.getBaseMinPrice());

                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, hotelVo.getGoogleLon().toString(), hotelVo.getGoogleLat().toString());

                    String distanceNum;
                    if (aDouble.toString().substring(aDouble.toString().indexOf(".") + 1, aDouble.toString().indexOf(".") + 2).equals("0")){
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf("."));
                    }
                    else {
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf(".") + 2);
                    }

                    parameterHotelVo.setDistance(distanceNum);
                    parameterHotelVoList.add(parameterHotelVo);
                }

                //根据指定酒店与周边各个酒店的直线距离从进到远排序
                parameterHotelVoList = parameterHotelVoList.stream().sorted(Comparator.comparing(ParameterHotelVo::getDistance)).collect(Collectors.toList());
//                parameterHotelVoList.sort((x, y) -> Double.compare(new Double(x.getDistance()), new Double(y.getDistance())));
                //酒店数量大于4个，减少显示酒店的数量
                if (parameterHotelVoList.size() > 4){
                    List<ParameterHotelVo> parameterHotelVos = new ArrayList<>();
                    for (int i = 0 ; i < 4 ; i++) {
                        parameterHotelVos.add(parameterHotelVoList.get(i));
                    }
                    parameterHotelVoList = parameterHotelVos;
                }

                return parameterHotelVoList;
            }
            else {
                throw new Exception("周边没有酒店");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 查询酒店周边交通
     * */
    @Override
    public List<HotelTransportationVo> selectTrafficAround(String lng, String lat) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        if (lng != null && !lng.equals("") && lat != null && !lat.equals("")){
            List<HotelTransportationVo> hotelTransportationVoList = new ArrayList<>();
            double distance = 2500;
            Map<String, Double> around = latitudeUtil.getAround(new Double(lng), new Double(lat), distance);

            List<DicSubwayStation> dicSubwayStations = dicSubwayStationMapper.selectDicSubwayStationLngAndLat(around.get("minLng"), around.get("maxLng"), around.get("minLat"), around.get("maxLat"));
            List<DicAirportStation> dicAirportStations = dicAirportStationMapper.selectDicAirportStationLngAndLat(around.get("minLng"), around.get("maxLng"), around.get("minLat"), around.get("maxLat"));

            HotelTransportationVo trafficAround = new HotelTransportationVo();
            trafficAround.setTrafficType("地铁");
            List<TransportationVo> transportationVoList = new ArrayList<>();
            if (dicSubwayStations != null && dicSubwayStations.size() > 0){
                for (DicSubwayStation dicSubwayStation : dicSubwayStations) {
                    TransportationVo transportationVo = new TransportationVo();
                    transportationVo.setTrafficId(dicSubwayStation.getId());
                    transportationVo.setTrafficName(dicSubwayStation.getStationName());
                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, String.valueOf(dicSubwayStation.getGoogleLon()), String.valueOf(dicSubwayStation.getGoogleLat()));
                    String substring = String.valueOf(aDouble).substring(0, String.valueOf(aDouble).indexOf("."));
                    if (Integer.parseInt(substring) > 1000){
                        substring = (Integer.parseInt(substring) / 1000) + "." + ((Integer.parseInt(substring) / 1000) / 100);
                    }

                    transportationVo.setDistance(substring);
                    transportationVoList.add(transportationVo);
                }
                trafficAround.setTransportationVoList(transportationVoList);
            }
            else {
                trafficAround.setTransportationVoList(null);
            }
            hotelTransportationVoList.add(trafficAround);


            HotelTransportationVo train = new HotelTransportationVo();
            train.setTrafficType("火车站");
            List<TransportationVo> traninList = new ArrayList<>();
            if (dicAirportStations != null && dicAirportStations.size() > 0){
                for (DicAirportStation dicAirportStation : dicAirportStations) {
                    TransportationVo transportationVo = new TransportationVo();
                    transportationVo.setTrafficId(dicAirportStation.getId());
                    transportationVo.setTrafficName(dicAirportStation.getAirportStationName());
                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, String.valueOf(dicAirportStation.getGoogleLon()), String.valueOf(dicAirportStation.getGoogleLat()));
                    String substring = String.valueOf(aDouble).substring(0, String.valueOf(aDouble).indexOf("."));
                    if (Integer.parseInt(substring) > 1000){
                        substring = (Integer.parseInt(substring) / 1000) + "." + ((Integer.parseInt(substring) / 1000) / 100);
                    }
                    transportationVo.setDistance(substring);
                    traninList.add(transportationVo);
                }
                train.setTransportationVoList(traninList);
            }
            else {
                train.setTransportationVoList(null);
            }

            hotelTransportationVoList.add(train);

            return hotelTransportationVoList;
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 查询酒店周边景点
     * */
    @Override
    public List<AttractionsVo> selectAttractions(String lng, String lat) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        if (lng != null && !lng.equals("") && lat != null && !lat.equals("")){
            List<AttractionsVo> attractionsVoList = new ArrayList<>();
            double distance = 5000;
            Map<String, Double> around = latitudeUtil.getAround(new Double(lng), new Double(lat), distance);
            List<DicLankMark> dicLankMarkList = dicLankMarkMapper.attractionsList(around.get("maxLng"), around.get("minLng"), around.get("maxLat"), around.get("minLat"));
            if (dicLankMarkList != null && dicLankMarkList.size() > 0){
                for (DicLankMark dicLankMark : dicLankMarkList) {
                    AttractionsVo attractionsVo = new AttractionsVo();
                    attractionsVo.setAttractionsId(dicLankMark.getId());
                    attractionsVo.setAttractionsName(dicLankMark.getLandMarkName());

                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, String.valueOf(dicLankMark.getGoogleLon()), String.valueOf(dicLankMark.getGoogleLat()));
                    String substring = String.valueOf(aDouble).substring(0, String.valueOf(aDouble).indexOf("."));
                    if (Integer.parseInt(substring) > 1000){
                        substring = (Integer.parseInt(substring) / 1000) + "." + ((Integer.parseInt(substring) / 1000) / 100);
                    }

                    attractionsVo.setAttractionsDistance(substring);
                    attractionsVoList.add(attractionsVo);
                }
                return attractionsVoList;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 酒店订单详情
     * */
    @Override
    public HotelOrderDetailsVo selectHotelOrderDetails(Long orderId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (orderId != null && orderId != 0){
            HotelOrder hotelOrder = hotelOrderMapper.checkHotelReservations(orderId);
            List<HotelOrderRoom> hotelOrderRooms = hotelOrderRoomMapper.checkHotelReservationsDetails(Long.valueOf(hotelOrder.getOrderNum()));

            if (hotelOrder != null && hotelOrderRooms != null && hotelOrderRooms.size() > 0){
                HotelOrderDetailsVo hotelOrderDetailsVo = new HotelOrderDetailsVo();
                hotelOrderDetailsVo.setOrderId(orderId);//酒店订单id
                hotelOrderDetailsVo.seteLongOrderId(hotelOrder.getELongOrderId());//艺龙订单号
                hotelOrderDetailsVo.setHotelName(hotelOrder.getHotelname());//酒店名称
                hotelOrderDetailsVo.setCreateTime(format.format(hotelOrder.getCreateTime()));//预定时间
                hotelOrderDetailsVo.setHotelContact(hotelOrder.getHotelphone());//酒店联系人信息
                if (hotelOrder.getHotelconfirmtype() != null && hotelOrder.getHotelconfirmtype() == 2){
                    hotelOrderDetailsVo.setHotelConfirmType("书面确认");//确认方式
                }
                else if (hotelOrder.getHotelconfirmtype() != null && hotelOrder.getHotelconfirmtype() == 3){
                    hotelOrderDetailsVo.setHotelConfirmType("口头确认");//确认方式
                }

//                hotelOrderDetailsVo.setInsured();//是否保价
                hotelOrderDetailsVo.setPpEmployeeName(hotelOrder.getEmployeename());//制单人

                HotelOrdersourcetype hotelOrdersourcetype = hotelOrdersourcetypeMapper.selectHotelOrdersource(hotelOrder.getOrdersourcetypeid());
                if (hotelOrdersourcetype != null){
                    hotelOrderDetailsVo.setOrderSourceTypeName(hotelOrdersourcetype.getOrdersourcename());//订单来源
                }

                HotelOrderoccupttype hotelOrderoccupttype = hotelOrderoccupttypeMapper.selectHotelOrderoccupt(hotelOrder.getOrderoccupttypeid());
                if (hotelOrderoccupttype != null){
                    hotelOrderDetailsVo.setOrderOccuptType(hotelOrderoccupttype.getOrderoccupttypename());//预定类型
                }

                if (hotelOrder.getOrdertype() == 1){
                    hotelOrderDetailsVo.setPaymentMethod("现付");//付款方式
                }
                else if (hotelOrder.getOrdertype() == 3){
                    hotelOrderDetailsVo.setPaymentMethod("预付");//付款方式
                }

//                hotelOrderDetailsVo.setInsuredTime();//保价截止时间
//                hotelOrderDetailsVo.setRoomTypeName();//客房类型
//                hotelOrderDetailsVo.setHotelCategory();//宾馆类别
                hotelOrderDetailsVo.setNumberOfRooms(hotelOrder.getNumberOfRooms().toString());//间数
                hotelOrderDetailsVo.setArriveTime(hotelOrder.getArrivetime());//入住时间
                hotelOrderDetailsVo.setCheckOutTime(hotelOrder.getCheckouttime());//离店时间

                String betweenDays = getBetweenDays(hotelOrder.getArrivetime(), hotelOrder.getCheckouttime());
                hotelOrderDetailsVo.setCheckInTime(betweenDays);//天数
                hotelOrderDetailsVo.setPricePeriod(hotelOrder.getArrivetime() + "--" + hotelOrder.getCheckouttime());//价格期间
                hotelOrderDetailsVo.setPayAmount(hotelOrder.getPayAmount());//价格
                hotelOrderDetailsVo.setProfit("***");//利润
                hotelOrderDetailsVo.setTotalAmount(hotelOrder.getPayAmount());//总计金额
                hotelOrderDetailsVo.setArrivalDate(hotelOrder.getArrivetime());//到店时间

                if (hotelOrder.getPayAmount() != null){
                    hotelOrderDetailsVo.setPaymentInformation("实付金额：" + hotelOrder.getPayAmount());//支付信息
                }
//                hotelOrderDetailsVo.setMethodToInforme();//通知方式
//                hotelOrderDetailsVo.setExtraMealRequest();//加餐要求
//                hotelOrderDetailsVo.setExtraBedRequest();//加床要求
//                hotelOrderDetailsVo.setPickUpRequirements();//接机要求
//                hotelOrderDetailsVo.setAdditionalRequirements();//附加要求
//                hotelOrderDetailsVo.setSpecialRequirements();//特殊要求
//                hotelOrderDetailsVo.setCompanyNotes();//公司备注
                hotelOrderDetailsVo.setPrepaidInformation("订单编号：" + hotelOrder.getOrderid());//预付信息

                for (int i = 0 ; i < hotelOrderRooms.size() ; i++) {
                    if (i == 0){
                        hotelOrderDetailsVo.setGuestName(hotelOrderRooms.get(i).getGuestname());//入住人
                    }
                    else {
                        hotelOrderDetailsVo.setGuestName(hotelOrderDetailsVo.getGuestName() + "," + hotelOrderRooms.get(i).getGuestname());//入住人
                    }
                    hotelOrderDetailsVo.setBreakfast(hotelOrderRooms.get(i).getBreakfastdesc());//早餐
                }

//                hotelOrderDetailsVo.setContact();//联系人

                return hotelOrderDetailsVo;
            }
            else {
                throw new Exception("没有这笔订单信息");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    public static String getBetweenDays(String startTimeStr, String endTimeStr) {
        int betweenDays = 0;
        Date startTime = strToDateLong(startTimeStr);
        Date endTime = strToDateLong(endTimeStr);

        long start = startTime.getTime();
        long end = endTime.getTime();

        betweenDays = (int) (Math.abs(end - start)/(24*3600*1000));

        return String.valueOf(betweenDays);
    }

    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 条件查询酒店订单列表
     * */
    @Override
    public HotelOrderPaginationVo conditionHotelOrder(HotelParameterVo hotelParameterVo) throws Exception {
        VipCustomerVo vipCustomerVo = new VipCustomerVo();

        //会员卡号
        if (hotelParameterVo.getCustomerCard() != null && !hotelParameterVo.getCustomerCard().equals("")){
            vipCustomerVo.setCardCode(hotelParameterVo.getCustomerCard());
        }
        //会员姓名
        if (hotelParameterVo.getCustomerName() != null && !hotelParameterVo.getCustomerName().equals("")){
            vipCustomerVo.setCustomerName(hotelParameterVo.getCustomerName());
        }
        //城市名称
        if (hotelParameterVo.getCityName() != null && !hotelParameterVo.getCityName().equals("")){
            DicProvince dicProvince = dicProvinceMapper.selectDicProvinceByProvinceName("%" + hotelParameterVo.getCityName() + "%");
            if (dicProvince.getId() != null && dicProvince.getId() != 0){
                hotelParameterVo.setProvinceId(dicProvince.getId());
            }
            else {
                throw new Exception("没有该城市信息");
            }
        }
        List<Long> orderId = new ArrayList<>();
        //订单号
        if (hotelParameterVo.getOrderNumber() != null && hotelParameterVo.getOrderNumber() != 0){
            orderId.add(hotelParameterVo.getOrderNumber());
        }
        //入住人姓名
        if (hotelParameterVo.getCheckName() != null && !hotelParameterVo.getCheckName().equals("")){
            List<HotelOrderRoom> hotelOrderRooms = hotelOrderRoomMapper.selectHotelOrderRoomByGuestname(hotelParameterVo.getCheckName());
            if (hotelOrderRooms != null && hotelOrderRooms.size() > 0){

                for (HotelOrderRoom hotelOrderRoom : hotelOrderRooms) {
                    orderId.add(hotelOrderRoom.getOrderid());
                }
            }
            else {
                throw new Exception("没有该入住人数据");
            }
        }
        if (orderId != null && orderId.size() > 0){
            hotelParameterVo.setOrderIdList(orderId);
        }

        //支付方式
        if (hotelParameterVo.getPayWay() != null && hotelParameterVo.getPayWay() != 0){
            hotelParameterVo.setGuarantee(null);
        }

        Long customerId = remoteCustomerService.customerByCustomerName(vipCustomerVo);
        if (customerId != null && customerId != 0){
            hotelParameterVo.setCustomerId(customerId);
        }

        hotelParameterVo.setPagesNum((hotelParameterVo.getPagesNum() - 1) * hotelParameterVo.getBarsNum());

        List<HotelOrder> hotelOrders = hotelOrderMapper.selectHotelOrderCondition(hotelParameterVo);

        List<HotelOrder> hotelOrderList = new ArrayList<>();
        if (hotelOrders != null && hotelOrders.size() > 0){
            for (int i = hotelParameterVo.getPagesNum() ; i < hotelOrders.size() ; i++){
                if (hotelOrderList.size() < hotelParameterVo.getBarsNum()){
                    hotelOrderList.add(hotelOrders.get(i));
                }
                else {
                    break;
                }
            }

            HotelOrderPaginationVo hotelOrderPaginationVo = new HotelOrderPaginationVo();
            hotelOrderPaginationVo.setTotalNumber(hotelOrders.size());
            hotelOrderPaginationVo.setShowNumber(hotelParameterVo.getBarsNum());
            hotelOrderPaginationVo.setHotelOrderListVo(hotelOrderListVo(hotelOrderList));
            return hotelOrderPaginationVo;
        }
        else {
            return null;
        }
    }

    /**
     * 会员订单列表
     * */
    @Override
    public List<BackHotelOrderVo> selectHotelOrderByCustomerId(Long customerId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<HotelOrder> hotelOrderList = hotelOrderMapper.selectHotelOrderByCustomerId(customerId);
        if (hotelOrderList != null && hotelOrderList.size() > 0){
            List<BackHotelOrderVo> backHotelOrderVoList = new ArrayList<>();
            for (HotelOrder hotelOrder : hotelOrderList) {
                try {
                    BackHotelOrderVo backHotelOrderVo = new BackHotelOrderVo();
                    backHotelOrderVo.setOrderId(hotelOrder.getOrderid());
                    backHotelOrderVo.setOrderNum(hotelOrder.getOrderNum());
                    backHotelOrderVo.setHotelName(hotelOrder.getHotelname());
                    backHotelOrderVo.setCreateTime(format.format(hotelOrder.getCreateTime()));
                    backHotelOrderVo.setArriveTime(hotelOrder.getArrivetime());
                    backHotelOrderVo.setCheckOutTime(hotelOrder.getCheckouttime());

                    com.ktgj.hotel.domain.HotelOrderStatus hotelOrderStatus = hotelOrderStatusMapper.selectHotelOrderStatusByid(hotelOrder.getOrderstatusid());
                    backHotelOrderVo.setOrderStatusName(hotelOrderStatus.getOrderstatusname());

                    HotelOrderFlowstatus hotelOrderFlowstatus = hotelOrderFlowstatusMapper.selectHotelOrderFlowstatusByid(hotelOrder.getOrderflowstatusid());
                    backHotelOrderVo.setOrderFlowStatusName(hotelOrderFlowstatus.getOrderflowname());
                    backHotelOrderVoList.add(backHotelOrderVo);
                } catch (Exception e){
                    throw new Exception(hotelOrder.getOrderid().toString());
                }
            }
            return backHotelOrderVoList;
        }
        else {
            throw new Exception("没有数据");
        }
    }

    /**
     * 酒店无卡无密/语音支付
     * */
    @Override
    public String hotelPay(HotelPayVo hotelPayVo, HttpServletRequest request) throws Exception {
        HotelOrder moneyAmout = hotelOrderMapper.selectHotelOrderByOrderNum(hotelPayVo.jsjOrderId);
//        BigDecimal amout = new BigDecimal(hotelPayVo.moneyAmout);
//        int i = moneyAmout.getPayAmount().compareTo(amout);

        //hotelPayVo.moneyAmout = "0.1";
//        if (i == 0){

            HotelOrder hotelOrderStart = new HotelOrder();
            hotelOrderStart.setOrderNum(hotelPayVo.jsjOrderId);
            hotelOrderStart.setSourceWay(hotelPayVo.payType);
            int i = hotelOrderMapper.updateSource(hotelOrderStart);
            hotelOrderStart.setOrderid(moneyAmout.getOrderid());
            if (i <= 0){
                System.out.println("订单来源修改失败");
            }

            if (hotelPayVo.amount != null && hotelPayVo.amount.compareTo(new BigDecimal(0)) > 0){
                hotelPayVo.moneyAmout = String.valueOf(new BigDecimal(hotelPayVo.moneyAmout).subtract(hotelPayVo.amount));

                String token = request.getHeader("token");
                Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
                if (employee != null){

                    moneyAmout.setDepositAmount(hotelPayVo.amount);
                    i = hotelOrderMapper.updateHotelOrder(moneyAmout);
                    if (i <= 0){
                        throw new Exception("修改订单预留款失败");
                    }

                    DepositBusinessApi depositBusiness = new DepositBusinessApi();
                    if (hotelPayVo.type != null && hotelPayVo.type.equals("yeeBao")){
                        depositBusiness.setRemark("酒店银行卡支付");
                    }
                    else if (hotelPayVo.type != null && hotelPayVo.type.equals("voice")){
                        depositBusiness.setRemark("酒店语音支付");
                    }
                    else if (hotelPayVo.type != null && hotelPayVo.type.equals("unionPay")){
                        depositBusiness.setRemark("酒店二维码支付");
                    }
                    else {
                        throw new Exception("无效的支付类型");
                    }

                    depositBusiness.setState("false");
                    depositBusiness.setBusinessType(EmHelper.businessType.HOTEL.getValue());
                    depositBusiness.setOperatorId(employee.getEmployeeId());
                    depositBusiness.setOrdersourceid(hotelPayVo.payType);
                    depositBusiness.setCustomerId(moneyAmout.getCustomerid());
                    depositBusiness.setDetailamount(hotelPayVo.amount);
                    depositBusiness.setChangetype(2l);
                    depositBusiness.setLockState("false");
                    depositBusiness.setOrderId(Long.valueOf(hotelPayVo.jsjOrderId));
                    depositBusiness.setDrawState("false");
                    Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
                    if (aLong <= 0){
                        throw new Exception("添加预留款记录失败");
                    }

                    Map<String, Object> map = new HashMap<>();
                    map.put("id", aLong);

                    if (hotelPayVo.type != null && hotelPayVo.type.equals("yeeBao")){
                        map.put("remark", "酒店银行卡支付");
                    }
                    else if (hotelPayVo.type != null && hotelPayVo.type.equals("voice")){
                        map.put("remark", "酒店语音支付");
                    }
                    else if (hotelPayVo.type != null && hotelPayVo.type.equals("unionPay")){
                        map.put("remark", "酒店二维码支付");
                    }
                    else {
                        throw new Exception("无效的支付类型");
                    }

                    boolean b = remoteCustomerService.manageAudit(map);
                    if (!b){
                        throw new Exception("审核失败，请进行人工审核");
                    }
                }
                else {
                    throw new Exception("登录已过期");
                }
            }

            if (new BigDecimal(hotelPayVo.moneyAmout).compareTo(new BigDecimal(0)) == 1){
                if (hotelPayVo.type != null && hotelPayVo.type.equals("yeeBao")){
                    CustomerApi customer = new CustomerApi();
                    customer.setCustCertificateNo(hotelPayVo.custCertificateNo);
                    customer.setContractPhoneOne(hotelPayVo.contractPhoneOne);
                    //银行卡信息
                    BankCardApi card = new BankCardApi();
                    card.setCardNumber(hotelPayVo.cardNumber);
                    card.setCardholder(hotelPayVo.cardholder);

                    Map<String, Object> map = new HashMap<>();
                    map.put("cardNumber", hotelPayVo.cardNumber);
                    String backCard = remoteCustomerService.backCard(map);

                    card.bankCode = backCard + "CREDIT";
                    if (hotelPayVo.creditCardTime != null && !hotelPayVo.creditCardTime.equals("") &&
                            hotelPayVo.Cvv2 != null && !hotelPayVo.Cvv2.equals("")){
                        card.setCreditCardTime(hotelPayVo.creditCardTime);
                        card.setCvv2(hotelPayVo.Cvv2);
                    }

                    BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
                    bankPayInfoApi.setJsjOrderId(hotelPayVo.jsjOrderId);
                    hotelPayVo.moneyAmout = "0.1";
                    bankPayInfoApi.setMoneyAmout(hotelPayVo.moneyAmout);
                    bankPayInfoApi.setCustomer(customer);
                    bankPayInfoApi.setCard(card);
                    bankPayInfoApi.setPayType(hotelPayVo.payType);

                    YeeBaoResultApi yeeBaoResultApi;
                    if (hotelPayVo.creditCardTime != null && !hotelPayVo.creditCardTime.equals("") &&
                            hotelPayVo.Cvv2 != null && !hotelPayVo.Cvv2.equals("")){
                        yeeBaoResultApi = remotePayService.CreditSale(bankPayInfoApi);
                    }
                    else {
                        yeeBaoResultApi = remotePayService.DebitSale(bankPayInfoApi);
                    }
                    if (yeeBaoResultApi.getCode().equals("1")){

                        if (hotelPayVo.jsjOrderId != null) {
                            HotelOrder hotelOrder = new HotelOrder();
                            hotelOrder.setOrderstatusid(1l);
                            hotelOrder.setPlusmoneystatus(CustomerConstants.payd.getValue());
                            hotelOrder.setOrderNum(hotelPayVo.jsjOrderId);
                            int updateHotelOrder = hotelOrderMapper.tmpUpdateHotelOrder(hotelOrder);
                            if (updateHotelOrder <= 0){
                                log.error("易宝修改订单失败");
                                System.out.println("易宝修改订单失败");
                            }

                            HotelOrderPaydetail hotelOrderPaydetail = new HotelOrderPaydetail();
                            hotelOrderPaydetail.setOrderid(Long.valueOf(hotelPayVo.jsjOrderId));
                            if (hotelPayVo.creditCardTime != null && !hotelPayVo.creditCardTime.equals("") &&
                                    hotelPayVo.Cvv2 != null && !hotelPayVo.Cvv2.equals("")){
                                hotelOrderPaydetail.setPaytype(BusinessTypeConstants.BankDebit.getValue());
                            }
                            else {
                                hotelOrderPaydetail.setPaytype(BusinessTypeConstants.BankCredit.getValue());
                            }
                            hotelOrderPaydetail.setHmac(yeeBaoResultApi.getTrxId());
                            int updatePayType = hotelOrderPaydetailMapper.updatePayType(hotelOrderPaydetail);
                            if (updatePayType <= 0){
                                log.error("易宝修改支付信息失败");
                                System.out.println("易宝修改支付信息失败");
                            }

                            CreateOrderResult order = null;

                            try {
                                order = bankCreateOrder(Long.valueOf(hotelPayVo.jsjOrderId), hotelPayVo.cardNumber);
                            } catch (Exception e) {

                            }

                            if (order.Code.equals("0")) {
                                log.error("艺龙下单成功");
                                System.out.println("艺龙下单成功");
                            } else {
                                log.error("艺龙下单失败" + order.Code);
                                System.out.println("艺龙下单失败" + order.Code);
                            }
                        }
                        List<HotelOrderAssist> hotelOrderAssists = hotelOrderAssistMapper.selectHotelOrderAssistListByOrderId(Long.valueOf(hotelOrderStart.getOrderid()));
                        if (hotelOrderAssists != null && hotelOrderAssists.size() > 0)
                            hotelOrderAssist(hotelOrderStart, hotelOrderAssists);
                        return "支付成功";
                    }
                    else {

                        HotelOrderException hotelOrderException = new HotelOrderException();

                        List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelPayVo.jsjOrderId);
                        if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
                            String person = null;
                            for (int n = 0; n < hotelOrderRoomList.size(); n++) {
                                if (n == 0){
                                    person = hotelOrderRoomList.get(n).getGuestname();
                                }
                                else {
                                    person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
                                }
                            }
                            hotelOrderException.setPerson(person);
                        }
                        hotelOrderException.setPersonPhone(moneyAmout.getPhone());
                        hotelOrderException.setHotelName(moneyAmout.getHotelname());
                        hotelOrderException.setReserveTime(moneyAmout.getCreateTime());
                        hotelOrderException.setExceptionInfo("支付失败");
                        hotelOrderException.setSourceWay("App");
                        hotelOrderException.setStatus("processed");
                        hotelOrderException.setOrderId(moneyAmout.getOrderid().toString());
                        hotelOrderException.setOrderType("reserve");
                        hotelOrderException.setEmployeeId(10l);
                        hotelOrderException.setCustomerId(moneyAmout.getCustomerid());
                        hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);

                        return yeeBaoResultApi.getErrorMsg();
                    }
                }
                else if (hotelPayVo.type != null && hotelPayVo.type.equals("voice")){
                    Map<String, Object> voice = new HashMap<>();
                    voice.put("mobileNumber", hotelPayVo.contractPhoneOne);
                    voice.put("bankCardNo", hotelPayVo.cardNumber);
                    voice.put("idCardNo", hotelPayVo.custCertificateNo);
                    voice.put("idCardName", hotelPayVo.cardholder);
                    hotelPayVo.moneyAmout = "0.1";
                    int parseInt = Integer.parseInt(hotelPayVo.moneyAmout) * 100;
                    voice.put("orderAmount", parseInt);
                    voice.put("orderId", hotelPayVo.jsjOrderId);
                    voice.put("asynAddress", "http://106.38.39.137:8080/hotel/callback/hotelVoicePayCallback");

                    String voicePay = remotePayService.voicePay(voice);

                    String newVoicePay = "支付失败";
                    if (voicePay != null){
                        newVoicePay = voicePay.substring(0, voicePay.indexOf(","));
//                String voicePayNew = voicePay.substring(voicePay.indexOf(",") + 1);
                        if (newVoicePay.equals("请注意来电")){
                            return newVoicePay;
                        }
                        else {

                            HotelOrderException hotelOrderException = new HotelOrderException();

                            List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelPayVo.jsjOrderId);
                            if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
                                String person = null;
                                for (int t = 0; t < hotelOrderRoomList.size(); t++) {
                                    if (t == 0){
                                        person = hotelOrderRoomList.get(t).getGuestname();
                                    }
                                    else {
                                        person = person + "|" + hotelOrderRoomList.get(t).getGuestname();
                                    }
                                }
                                hotelOrderException.setPerson(person);
                            }
                            hotelOrderException.setPersonPhone(moneyAmout.getPhone());
                            hotelOrderException.setHotelName(moneyAmout.getHotelname());
                            hotelOrderException.setReserveTime(moneyAmout.getCreateTime());
                            hotelOrderException.setExceptionInfo("支付失败");
                            hotelOrderException.setSourceWay("App");
                            hotelOrderException.setStatus("processed");
                            hotelOrderException.setOrderId(moneyAmout.getOrderid().toString());
                            hotelOrderException.setOrderType("reserve");
                            hotelOrderException.setEmployeeId(10l);
                            hotelOrderException.setCustomerId(moneyAmout.getCustomerid());
                            hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
                            log.error("语音支付异常");
                            return "语音支付异常";
                        }
                    }
                    else {

                        HotelOrderException hotelOrderException = new HotelOrderException();

                        List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelPayVo.jsjOrderId);
                        if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
                            String person = null;
                            for (int k = 0; k < hotelOrderRoomList.size(); k++) {
                                if (k == 0){
                                    person = hotelOrderRoomList.get(k).getGuestname();
                                }
                                else {
                                    person = person + "|" + hotelOrderRoomList.get(k).getGuestname();
                                }
                            }
                            hotelOrderException.setPerson(person);
                        }
                        hotelOrderException.setPersonPhone(moneyAmout.getPhone());
                        hotelOrderException.setHotelName(moneyAmout.getHotelname());
                        hotelOrderException.setReserveTime(moneyAmout.getCreateTime());
                        hotelOrderException.setExceptionInfo("支付失败");
                        hotelOrderException.setSourceWay("App");
                        hotelOrderException.setStatus("processed");
                        hotelOrderException.setOrderId(moneyAmout.getOrderid().toString());
                        hotelOrderException.setOrderType("reserve");
                        hotelOrderException.setEmployeeId(10l);
                        hotelOrderException.setCustomerId(moneyAmout.getCustomerid());
                        hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);

                        return null;
                    }
                }
                else if (hotelPayVo.type != null && hotelPayVo.type.equals("unionPay")){
                    String billNo = hotelPayVo.jsjOrderId;
                    hotelPayVo.moneyAmout = "0.1";
                    String totalAmount = hotelPayVo.moneyAmout;
                    String notifyUrl = "http://106.38.39.137:8080/hotel/callback/hotelUnionQRCodePayCallback";
                    Map<String, String> map = new HashMap<>();
                    BigDecimal amount = new BigDecimal(billNo);
                    billNo = "5676" + amount;
                    map.put("billNo", billNo);
                    map.put("totalAmount", String.valueOf(new BigDecimal(totalAmount).multiply(new BigDecimal(100)).longValue()));
                    map.put("notifyUrl", notifyUrl);
                    UnionPayQRCodeResponseApi qrCode = remotePayService.getQRCode(map);
                    if (qrCode.getBillQRCode() != null && !qrCode.getBillQRCode().equals("")){
                        HotelOrder hotelOrder = new HotelOrder();
                        hotelOrder.setOrderNum("5676" + hotelPayVo.jsjOrderId);
                        hotelOrder.setQrCard(qrCode.getBillQRCode());
                        int updateState = hotelOrderMapper.tmpUpdateHotelOrder(hotelOrder);
                        if (updateState <= 0){
                            System.out.println("二维码修改订单失败");
                        }
                        List<HotelOrderAssist> hotelOrderAssists = hotelOrderAssistMapper.selectHotelOrderAssistListByOrderId(Long.valueOf(hotelOrderStart.getOrderid()));
                        if (hotelOrderAssists != null && hotelOrderAssists.size() > 0)
                            hotelOrderAssist(hotelOrderStart, hotelOrderAssists);
                        return qrCode.getBillQRCode();
                    }
                    else {
                        HotelOrderException hotelOrderException = new HotelOrderException();

                        List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelPayVo.jsjOrderId);
                        if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
                            String person = null;
                            for (int j = 0; j < hotelOrderRoomList.size(); j++) {
                                if (j == 0){
                                    person = hotelOrderRoomList.get(j).getGuestname();
                                }
                                else {
                                    person = person + "|" + hotelOrderRoomList.get(j).getGuestname();
                                }
                            }
                            hotelOrderException.setPerson(person);
                        }
                        hotelOrderException.setPersonPhone(moneyAmout.getPhone());
                        hotelOrderException.setHotelName(moneyAmout.getHotelname());
                        hotelOrderException.setReserveTime(moneyAmout.getCreateTime());
                        hotelOrderException.setExceptionInfo("支付失败");
                        hotelOrderException.setSourceWay("App");
                        hotelOrderException.setStatus("processed");
                        hotelOrderException.setOrderId(moneyAmout.getOrderid().toString());
                        hotelOrderException.setOrderType("reserve");
                        hotelOrderException.setEmployeeId(10l);
                        hotelOrderException.setCustomerId(moneyAmout.getCustomerid());
                        hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);

                        return qrCode.getErrMsg();
                    }
                }
                else {
                    log.error("无效的支付类型");
                    throw new Exception("无效的支付类型");
                }
            }
            else {
                if (hotelPayVo.jsjOrderId != null) {
                    HotelOrder hotelOrder = new HotelOrder();
                    hotelOrder.setOrderstatusid(1l);
                    hotelOrder.setPlusmoneystatus(CustomerConstants.payd.getValue());
                    hotelOrder.setOrderNum(hotelPayVo.jsjOrderId);
                    int updateHotelOrder = hotelOrderMapper.tmpUpdateHotelOrder(hotelOrder);
                    if (updateHotelOrder <= 0){
                        log.error("易宝修改订单失败");
                        System.out.println("易宝修改订单失败");
                    }

                    HotelOrderPaydetail hotelOrderPaydetail = new HotelOrderPaydetail();
                    hotelOrderPaydetail.setOrderid(Long.valueOf(hotelPayVo.jsjOrderId));
                    if (hotelPayVo.creditCardTime != null && !hotelPayVo.creditCardTime.equals("") &&
                            hotelPayVo.Cvv2 != null && !hotelPayVo.Cvv2.equals("")){
                        hotelOrderPaydetail.setPaytype(BusinessTypeConstants.BankDebit.getValue());
                    }
                    else {
                        hotelOrderPaydetail.setPaytype(BusinessTypeConstants.BankCredit.getValue());
                    }
                    
                    int updatePayType = hotelOrderPaydetailMapper.updatePayType(hotelOrderPaydetail);
                    if (updatePayType <= 0){
                        log.error("易宝修改支付信息失败");
                        System.out.println("易宝修改支付信息失败");
                    }

                    CreateOrderResult order = null;

                    try {
                        order = bankCreateOrder(Long.valueOf(hotelPayVo.jsjOrderId), hotelPayVo.cardNumber);
                    } catch (Exception e) {
                        return e.getMessage();
                    }

                    if (order.Code.equals("0")) {
                        log.error("艺龙下单成功");
                        System.out.println("艺龙下单成功");
                    } else {
                        log.error("艺龙下单失败" + order.Code);
                        System.out.println("艺龙下单失败" + order.Code);
                    }
                }
                List<HotelOrderAssist> hotelOrderAssists = hotelOrderAssistMapper.selectHotelOrderAssistListByOrderId(Long.valueOf(hotelOrderStart.getOrderid()));
                if (hotelOrderAssists != null && hotelOrderAssists.size() > 0)
                    hotelOrderAssist(hotelOrderStart, hotelOrderAssists);
                return "支付成功";
            }

//        }
//        else {
//            return "支付金额发生变化";
//        }
    }

    /**
     * 酒店支付宝支付
     * */
    @Override
    public String aliPayCallback(BigDecimal money, String orderNumber, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        String token = request.getHeader("token");
        Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
        if (employee == null){
            throw new Exception("登陆已过期");
        }

        if (amount.compareTo(new BigDecimal(0)) > 0){
            money = money.subtract(amount);

            HotelOrder hotelOrder = hotelOrderMapper.selectHotelOrderByOrderNum(orderNumber);
            hotelOrder.setDepositAmount(amount);
            int i = hotelOrderMapper.updateHotelOrder(hotelOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("酒店支付宝支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.HOTEL.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(hotelOrder.getCustomerid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderNumber));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("天机预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "酒店支付宝支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("payMoney", money);
        map.put("orderNumber", orderNumber);
        map.put("notifyUrl", "http://106.38.39.137:8080/hotel/callback/hotelAliPayCallback");
        String postAliPayParam = remotePayService.postAliPayParam(map);
        if (postAliPayParam != null && !postAliPayParam.equals("")){
            return postAliPayParam;
        }
        else {
            return null;
        }
    }

    /**
     * 酒店银联支付
     * */
    @Override
    public String unionPayCallback(String orderIdParam, BigDecimal priceParam, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        String token = request.getHeader("token");
        Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
        if (employee != null){
            throw new Exception("登录已过期");
        }

        if (amount.compareTo(new BigDecimal(0)) > 0){
            priceParam = priceParam.subtract(amount);

            HotelOrder hotelOrder = hotelOrderMapper.selectHotelOrderByOrderNum(orderIdParam);
            hotelOrder.setDepositAmount(amount);
            int i = hotelOrderMapper.updateHotelOrder(hotelOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("酒店支付宝支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.HOTEL.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(hotelOrder.getCustomerid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderIdParam));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("天机预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "酒店支付宝支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("orderIdParam", orderIdParam);
        map.put("priceParam", priceParam);
        map.put("notifyUrl", "http://106.38.39.137:8080/hotel/callback/hotelUnionPayCallback");
        String postAliPayParam = remotePayService.postUnionPayParam(map);
        if (postAliPayParam != null && !postAliPayParam.equals("")){
            return postAliPayParam;
        }
        else {
            return null;
        }
    }

    /**
     * 酒店介绍(新)
     * @param hotelId
     * @return
     */
    @Override
    public HotelHomeDetailInfo queryHotelDetail(String hotelId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        HotelDetailInput input = new HotelDetailInput();
        Date time = new Date();
        input.ArrivalDate = format.format(time);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.DATE, 1);
        input.DepartureDate = format.format(calendar.getTime());

        input.HotelIds = hotelId;

        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }
        if (hotelDetailOutput.Result.getHotels() != null && hotelDetailOutput.Result.getHotels().size() > 0){
            HotelHomeDetailInfo hotelHomeDetailInfo = new HotelHomeDetailInfo();
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    hotelHomeDetailInfo.setName(hotel.getDetail().get(0).getHotelName());//酒店名称
                    hotelHomeDetailInfo.setAddress(detailBean.getAddress());//地址
                    hotelHomeDetailInfo.setGoogleLat(new Double(detailBean.getLatitude()));//纬度
                    hotelHomeDetailInfo.setGoogleLon(new Double(detailBean.getLongitude()));//经度
                    hotelHomeDetailInfo.setPhone(detailBean.getPhone());//酒店前台电话
                    hotelHomeDetailInfo.setHouse_intro(detailBean.getDescription());//酒店简介
                    hotelHomeDetailInfo.setCheckin_time("入住时间: "+ detailBean.getCheckInTime() + "以后 离店时间: " + detailBean.getCheckOutTime() + "以前");
                    hotelHomeDetailInfo.setChild("不接受18岁以下客人单独入住。 不接受18岁以下客人在无监护人陪同的情况下入住");
                }
            }
            return hotelHomeDetailInfo;
        }
        else {
            throw new Exception("未查到酒店信息");
        }
    }

    @Override
    public HotelDetailOutput orderDetails(Long id) throws Exception {
        HotelDetailOutput hotelDetailOutput = null;
        InputVo inputVo = new InputVo();
        inputVo.setOrderId(id);
        try {
            hotelDetailOutput = (HotelDetailOutput) getResult(hotelDetailOutput, inputVo, HotelUtils.HOTEL_ORDER_DETAIL);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }
        return hotelDetailOutput;
    }

    /**
     * 查询待填写订单
     * */
    @Override
    public SelInterfaceVo selInterface(HotelDetailInput input) throws Exception {
        SelInterfaceVo selInterfaceVo = new SelInterfaceVo();
        selInterfaceVo.setRoomTypeId(input.RoomTypeId);
        selInterfaceVo.setRatePlanId(Long.valueOf(input.RatePlanId));
        HotelDetailOutput hotelDetailOutput = ElongUtils.queryByIdHotel(input);
        if (hotelDetailOutput.Result != null){

            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    selInterfaceVo.setHotelName(detailBean.getHotelName());
                    selInterfaceVo.setPhone(detailBean.getPhone());
                    selInterfaceVo.setAddress(detailBean.getAddress());
                }
            }

            List<HotelDetailOutputVo> hotelDetailOutputVoList;
            try {
                hotelDetailOutputVoList = hotelDetailOutputVo(hotelDetailOutput);
            } catch (Exception e){
                throw new Exception(e.getMessage());
            }

            if (hotelDetailOutputVoList != null && hotelDetailOutputVoList.size() > 0){
                for (HotelDetailOutputVo hotelDetailOutputVo : hotelDetailOutputVoList) {
                    for (RatePlansVo ratePlansVo : hotelDetailOutputVo.ratePlansVoList){
                        if (ratePlansVo.roomTypeId.equals(input.RoomTypeId) && ratePlansVo.ratePlanId == input.RatePlanId){
                            selInterfaceVo.setPaymentType(ratePlansVo.paymentType);
                            selInterfaceVo.setBookingRules(ratePlansVo.description);
                            selInterfaceVo.setBreakfast(Long.valueOf(ratePlansVo.breakfast));
                            selInterfaceVo.setPrice(ratePlansVo.price);
                            selInterfaceVo.setConfirmNow(ratePlansVo.confirmNow);
                            selInterfaceVo.setFreeCancellation(ratePlansVo.freeCancellation);
                            selInterfaceVo.setAvailableToOrder(ratePlansVo.availableToOrder);
                            selInterfaceVo.setRatePlanName(ratePlansVo.ratePlanName);
                            selInterfaceVo.setBedType(ratePlansVo.bedType);
                            selInterfaceVo.setWindows(ratePlansVo.windows);
                            if (ratePlansVo.guaranteeType != null && !ratePlansVo.guaranteeType.equals("")){
                                selInterfaceVo.setGuaranteeType(ratePlansVo.guaranteeType);
                            }
                            else if (ratePlansVo.roomCount != 0){
                                selInterfaceVo.setRoomCount(Long.valueOf(ratePlansVo.roomCount));
                            }
                            else if (ratePlansVo.arrivalTime != null && !ratePlansVo.arrivalTime.equals("")){

                                try {
                                    DateFormat format = new SimpleDateFormat("HH:mm");
                                    Calendar latestArrivalTime = Calendar.getInstance();
                                    latestArrivalTime.setTime(format.parse(input.LatestArrivalTime));//最晚到店时间
                                    Calendar arrivalTime = Calendar.getInstance();
                                    arrivalTime.setTime(format.parse(ratePlansVo.arrivalTime));//需要担保的到店时间
                                    if (latestArrivalTime.compareTo(arrivalTime) == -1){
                                        selInterfaceVo.setGuaranteeType("false");
                                    }
                                    else {
                                        selInterfaceVo.setGuaranteeType("true");
                                    }

                                } catch (Exception e){
                                    throw new Exception("最晚到店时间格式错误");
                                }
                            }
                        }
                    }
                }
            }
        }
        return selInterfaceVo;
    }

    /**
     * 推荐等级列表
     * */
    @Override
    public List<Long> recommendLevel() {
        List<Long> hotels = new ArrayList<>();
        List<Hotels> hotelList = hotelMapper.recommendLevel();
        if (hotelList != null && hotelList.size() > 0){
            for (Hotels hotel : hotelList) {
                if (hotel != null && hotel.getRecommendLevel() != null){
                    hotels.add(Long.valueOf(hotel.getRecommendLevel()));
                }
            }
        }
        return hotels;
    }

    @Override
    public List<Destination> destination(String name) {
        HotelDetailInput input = new HotelDetailInput();
        input.QueryText = name;
        input.SugOrientation = 0;
        HotelDetailOutput destination = ElongUtils.destination(input);

        List<Destination> destinationList = new ArrayList<>();
        if (destination != null &&
                destination.Result != null &&
                destination.Result.RegionResult != null &&
                destination.Result.RegionResult.size() > 0){
            for (RegionResult regionResult : destination.Result.RegionResult) {
                Destination tmpDestination = new Destination();
                tmpDestination.setRegionNameCn(regionResult.getRegionNameCn());
                tmpDestination.setParentId(regionResult.getParentId());
                tmpDestination.setParentNameCn(regionResult.getParentNameCn());
                tmpDestination.setComposedName(regionResult.getComposedName());
                destinationList.add(tmpDestination);
            }
        }
        return destinationList;
    }

    /**
     * 酒店订单条件查询结果整理
     * */
    public List<HotelOrderListVo> hotelOrderListVo(List<HotelOrder> hotelOrders){
        List<HotelOrderListVo> hotelOrderListVos = new ArrayList<>();

        for (HotelOrder hotelOrder : hotelOrders) {
//            HotelOrderRefundapply hotelOrderRefundapply = hotelOrderRefundapplyMapper.hotelOrderRefundapply(Long.valueOf(hotelOrder.getOrderNum()));
//            if (hotelOrderRefundapply == null){
//                continue;
//            }
            HotelOrderListVo hotelOrderListVo = new HotelOrderListVo();
            hotelOrderListVo.setPhone(hotelOrder.getPhone());
            hotelOrderListVo.setOrderId(hotelOrder.getOrderid());
            hotelOrderListVo.setOrderNum(hotelOrder.getOrderNum());
            hotelOrderListVo.seteLongOrderId(hotelOrder.getELongOrderId());
            hotelOrderListVo.setPlusMoneyStatus(hotelOrder.getPlusmoneystatus());
            hotelOrderListVo.setHotelName(hotelOrder.getHotelname());
            hotelOrderListVo.setOrderVersion(hotelOrder.getOrderversion());
            hotelOrderListVo.setCustomerId(hotelOrder.getCustomerid());
            List<HotelOrderRoom> hotelOrderRooms = hotelOrderRoomMapper.checkHotelReservationsDetails(hotelOrder.getOrderid());
            if (hotelOrderRooms != null && hotelOrderRooms.size() > 0){
                for (int i = 0 ; i < hotelOrderRooms.size() ; i++){
                    if (i == 0){
                        hotelOrderListVo.setGuestName(hotelOrderRooms.get(i).getGuestname());
                    }
                    else {
                        hotelOrderListVo.setGuestName(hotelOrderListVo.getGuestName() + "," + hotelOrderRooms.get(i).getGuestname());
                    }
                }
                hotelOrderListVo.setContactName(hotelOrderRooms.get(0).getGuestname());
            }
            hotelOrderListVo.setEmployeeName(hotelOrder.getEmployeename());

            HotelOrderFlowstatus hotelOrderFlowstatus = hotelOrderFlowstatusMapper.selectHotelOrderFlowstatusByid(hotelOrder.getOrderflowstatusid());
            if (hotelOrderFlowstatus != null){
                hotelOrderListVo.setOrderFlowStatusId(hotelOrder.getOrderflowstatusid());
                hotelOrderListVo.setOrderFlowStatusName(hotelOrderFlowstatus.getOrderflowname());
            }

            com.ktgj.hotel.domain.HotelOrderStatus hotelOrderStatus = hotelOrderStatusMapper.selectHotelOrderStatusByid(hotelOrder.getOrderstatusid());
            if (hotelOrderStatus != null){
                hotelOrderListVo.setOrderStatusId(hotelOrder.getOrderstatusid());
                hotelOrderListVo.setOrderStatusName(hotelOrderStatus.getOrderstatusname());
            }

            if (hotelOrder.getOrdertype() == 1){
                hotelOrderListVo.setPayWay("现付");
            }
            else if (hotelOrder.getOrdertype() == 3){
                hotelOrderListVo.setPayWay("预付");
            }

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            hotelOrderListVo.setArriveTime(hotelOrder.getArrivetime());
            hotelOrderListVo.setCheckOutTime(hotelOrder.getCheckouttime());
            if (hotelOrder.getCreateTime() != null){
                hotelOrderListVo.setCreateTime(format.format(hotelOrder.getCreateTime()));
            }
            hotelOrderListVo.setReserveTime(hotelOrder.getCheckInTime());
            hotelOrderListVo.setCheckInTime(hotelOrder.getCheckInTime());

            HotelOrdersourcetype hotelOrdersourcetype = hotelOrdersourcetypeMapper.selectHotelOrdersource(hotelOrder.getOrdersourcetypeid());
            if (hotelOrdersourcetype != null){
                hotelOrderListVo.setOrderSourceTypeName(hotelOrdersourcetype.getOrdersourcename());
            }

            hotelOrderListVos.add(hotelOrderListVo);
        }

        return hotelOrderListVos;
    }

    /**
     * 查询周边地铁站
     * */
    public List<TransportationVo> selectDicSubwayStationLngAndLat(String lng, String lat) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        if (lng != null && !lng.equals("") && lat != null && !lat.equals("")){
            double distance = 1000;
            Map<String, Double> around = latitudeUtil.getAround(new Double(lng), new Double(lat), distance);

            List<DicSubwayStation> dicSubwayStations = dicSubwayStationMapper.selectDicSubwayStationLngAndLat(around.get("minLng"), around.get("maxLng"), around.get("minLat"), around.get("maxLat"));

            if (dicSubwayStations != null && dicSubwayStations.size() > 0){
                List<TransportationVo> transportationVoList = new ArrayList<>();
                for (DicSubwayStation dicSubwayStation : dicSubwayStations) {
                    TransportationVo transportationVo = new TransportationVo();
                    transportationVo.setTrafficId(dicSubwayStation.getId());
                    transportationVo.setTrafficName(dicSubwayStation.getStationName());

                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, String.valueOf(dicSubwayStation.getGoogleLon()), String.valueOf(dicSubwayStation.getGoogleLat()));

                    String distanceNum;
                    if (aDouble.toString().substring(aDouble.toString().indexOf(".") + 1, aDouble.toString().indexOf(".") + 2).equals("0")){
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf("."));
                    }
                    else {
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf(".") + 2);
                    }

                    transportationVo.setDistance(distanceNum);
                    transportationVoList.add(transportationVo);
                }
                return transportationVoList;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 查询周边地铁站
     * */
    public List<TransportationVo> selectDicAirportStationLngAndLat(String lng, String lat) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        if (lng != null && !lng.equals("") && lat != null && !lat.equals("")){
            double distance = 2500;
            Map<String, Double> around = latitudeUtil.getAround(new Double(lng), new Double(lat), distance);

            List<DicAirportStation> dicAirportStations = dicAirportStationMapper.selectDicAirportStationLngAndLat(around.get("minLng"), around.get("maxLng"), around.get("minLat"), around.get("maxLat"));

            if (dicAirportStations != null && dicAirportStations.size() > 0){
                List<TransportationVo> transportationVoList = new ArrayList<>();
                for (DicAirportStation dicAirportStation : dicAirportStations) {
                    TransportationVo transportationVo = new TransportationVo();
                    transportationVo.setTrafficId(dicAirportStation.getId());
                    transportationVo.setTrafficName(dicAirportStation.getAirportStationName());

                    Double aDouble = gaoDeUtil.distanceMeter(lng, lat, String.valueOf(dicAirportStation.getGoogleLon()), String.valueOf(dicAirportStation.getGoogleLat()));

                    String distanceNum;
                    if (aDouble.toString().substring(aDouble.toString().indexOf(".") + 1, aDouble.toString().indexOf(".") + 2).equals("0")){
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf("."));
                    }
                    else {
                        distanceNum = aDouble.toString().substring(0, aDouble.toString().indexOf(".") + 2);
                    }

                    transportationVo.setDistance(distanceNum);
                    transportationVoList.add(transportationVo);
                }
                return transportationVoList;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后台酒店列表推荐等级赋值
     * */
    public String recommendLevel(Long id) throws Exception {
        String recommendLevelName = null;
        if (id != null && id != 0){
            switch (Integer.parseInt(id.toString())){
                case 0:
                case 1:
                case 2:
                    recommendLevelName = "客栈";
                    break;
                case 3:
                    recommendLevelName = "舒适";
                    break;
                case 4:
                    recommendLevelName = "高档";
                    break;
                case 5:
                    recommendLevelName = "豪华";
                    break;
                default:
                    throw new Exception("推荐等级不存在，请更新数据库" + id);
            }
        }
        return recommendLevelName;
    }

    /**
     * 酒店房型筛选（筛选）
     * */
    public HotelDetails filter(RoomTypeVo roomTypeVo, HotelDetailOutput hotelDetailOutput){
        HotelDetails hotelDetails = new HotelDetails();
        List<String> roomId = new ArrayList<>();
        List<String> valueAddId = new ArrayList<>();
        List<Long> prepayRuleId = new ArrayList<>();
        int count = 0;

        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            hotelDetails.HotelId = hotel.getHotelId();
            //床型：（大床/双床）单选
            if (roomTypeVo.getBedType() != null && !roomTypeVo.getBedType().equals("")){
                count = 1;
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    if (roomTypeVo.getBedType().equals(HotelEnum.RegionalLocation.BigBed.getValue())){//大床
                        if (room.getBedType().contains("大床")){
                            roomId.add(room.getRoomId());
                        }
                    }
                    else if (roomTypeVo.getBedType().equals(HotelEnum.RegionalLocation.DoubleBed.getValue())){//双床
                        if (room.getBedType().contains("双床")){
                            roomId.add(room.getRoomId());
                        }
                    }
                }
            }

            //早餐:多选
            if (roomTypeVo.getBreakfast() != null && roomTypeVo.getBreakfast().size() > 0){
                for (String breakfast : roomTypeVo.getBreakfast()) {
                    List<HotelDetailResponse.HotelsBean.ValueAdd> collect = hotel.getValueAdds().stream().filter(item -> item.getTypeCode().equals("99")).collect(Collectors.toList()); //特殊早餐
                    if (collect != null && collect.size() > 0) {
                        for (HotelDetailResponse.HotelsBean.ValueAdd valueAdd : collect) {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                long arrivalDate = dateFormat.parse(roomTypeVo.getArrivalDate()).getTime(); //到店日期
                                long departureDate = dateFormat.parse(roomTypeVo.getDepartureDate()).getTime(); //离店日期
                                if (arrivalDate > valueAdd.getStartDate().getTime() && departureDate < valueAdd.getEndDate().getTime()) {
                                    String[] arrSplit = roomTypeVo.getArrivalDate().split("-");
                                    String[] depSplit = roomTypeVo.getDepartureDate().split("-");
                                    List<LocalDate> allDatesInTheDateRange = getAllDatesInTheDateRange(LocalDate.of(Integer.parseInt(arrSplit[0]), Integer.parseInt(arrSplit[1]), Integer.parseInt(arrSplit[2])), LocalDate.of(Integer.parseInt(depSplit[0]), Integer.parseInt(depSplit[1]), Integer.parseInt(depSplit[2])));
                                    List<String> dateList = new ArrayList<>();
                                    Set<String> dateSet = new HashSet<>();
                                    if (CollectionUtils.isNotEmpty(allDatesInTheDateRange)) {
                                        for (LocalDate localDate : allDatesInTheDateRange) {
                                            String dateToWeek = dateToWeek(String.valueOf(localDate));
                                            dateList.add(dateToWeek);
                                        }
                                    }
                                    for (String date : dateList) {
                                        String conversionDate = conversionDate(date);
                                        dateSet.add(conversionDate);
                                    }
                                    String weekSet = "";
                                    for (String set : dateSet) {
                                        weekSet += set + ",";
                                    }
                                    if (valueAdd.getWeekSet().contains(weekSet)) {
                                        String valueAddIdTwo = valueAdd(breakfast, valueAdd, "");
                                        if (!valueAddIdTwo.equals(""))
                                            valueAddId.add(valueAddIdTwo);
                                    } else {
                                        for (HotelDetailResponse.HotelsBean.ValueAdd valueAddTwo : hotel.getValueAdds()) {
                                            String valueAddIdTwo = valueAdd(breakfast, valueAddTwo, "01");
                                            if (!valueAddIdTwo.equals(""))
                                                valueAddId.add(valueAddIdTwo);
                                        }
                                    }
                                } else {
                                    for (HotelDetailResponse.HotelsBean.ValueAdd valueAddTwo : hotel.getValueAdds()) {
                                        String valueAddIdTwo = valueAdd(breakfast, valueAddTwo, "01");
                                        if (!valueAddIdTwo.equals(""))
                                            valueAddId.add(valueAddIdTwo);
//                                        if (breakfast.equals(HotelEnum.RegionalLocation.WithoutBreakfast.getValue())){//不含早
//                                            if (valueAddTwo.getTypeCode().equals("01") && String.valueOf(valueAddTwo.isInclude()).equals("false")){
//                                                valueAddId.add(valueAddTwo.getValueAddId());
//                                            }
//                                        }
//                                        else if (valueAddTwo.getTypeCode().equals("01") && breakfast.equals(HotelEnum.RegionalLocation.BreakfastIncluded.getValue())){//含早餐
//                                            if (String.valueOf(valueAddTwo.isInclude()).equals("true")){
//                                                valueAddId.add(valueAddTwo.getValueAddId());
//                                            }
//                                        }
//                                        else {
//                                            if (breakfast.equals(HotelEnum.RegionalLocation.SingleBreakfast.getValue())){//单人早餐
//                                                if (valueAddTwo.getAmount() == 1){
//                                                    valueAddId.add(valueAddTwo.getValueAddId());
//                                                }
//                                            }
//                                            else if (breakfast.equals(HotelEnum.RegionalLocation.BreakfastForTwo.getValue())){//双人早餐
//                                                if (valueAddTwo.getAmount() == 2){
//                                                    valueAddId.add(valueAddTwo.getValueAddId());
//                                                }
//                                            }
//                                            else if (breakfast.equals(HotelEnum.RegionalLocation.Above.getValue())){//含三早及以上
//                                                if (valueAddTwo.getAmount() >= 3){
//                                                    valueAddId.add(valueAddTwo.getValueAddId());
//                                                }
//                                            }
//                                        }
                                    }
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        for (HotelDetailResponse.HotelsBean.ValueAdd valueAdd : hotel.getValueAdds()) {
                            String valueAddIdTwo = valueAdd(breakfast, valueAdd, "01");
                            if (!valueAddIdTwo.equals(""))
                                valueAddId.add(valueAddIdTwo);
                        }
                    }
                }
            }

            //服务：多选
            if (roomTypeVo.getServe() != null && roomTypeVo.getServe().size() > 0){
                for (String serve : roomTypeVo.getServe()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                            if (serve.equals(HotelEnum.RegionalLocation.SpecialTicketAvailable.getValue())){//可开专票
                                count = 1;
                                if (!room.getName().contains("普通")){//普通房不可开专票
                                    roomId.add(room.getRoomId());
                                }
                                else if (!ratePlan.getProductTypes().equals("4")){//钟点房不可开专票
                                    roomId.add(room.getRoomId());
                                }
                            }
                            else if (serve.equals(HotelEnum.RegionalLocation.ConfirmNow.getValue())){//立即确认
                                count = 1;
                                if (ratePlan.isInstantConfirmation()){
                                    roomId.add(room.getRoomId());
                                }
                            }
                            else if (serve.equals(HotelEnum.RegionalLocation.HotelPackage.getValue())){//酒店套餐
                                count = 1;
                                if (ratePlan.getPkgProductIds() != null){
                                    roomId.add(room.getRoomId());
                                }
                            }
                            for (HotelDetailResponse.HotelsBean.PrepayRulesBean prepayRule : hotel.getPrepayRules()) {
                                if (serve.equals(HotelEnum.RegionalLocation.FreeCancellation.getValue())){//免费取消
                                    if (prepayRule.getChangeRule().equals(HotelEnum.RegionalLocation.PrepayNeedSomeDay.getValue()) ||
                                            prepayRule.getChangeRule().equals(HotelEnum.RegionalLocation.PrepayNeedOneTime.getValue())){
                                        prepayRuleId.add(prepayRule.getPrepayRuleId());
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //优惠：多选
            if (roomTypeVo.getDiscount() != null && roomTypeVo.getDiscount().size() > 0){
                for (String discount : roomTypeVo.getDiscount()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                            if (discount.equals(HotelEnum.RegionalLocation.CashBack.getValue())){//有返现
                                count = 1;
                                if (ratePlan.getNightlyRates() != null && ratePlan.getNightlyRates().size() > 0){
                                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.NightlyRatesBean nightlyRate : ratePlan.getNightlyRates()) {
                                        if (nightlyRate.getCoupon() > 0){
                                            roomId.add(room.getRoomId());
                                        }
                                    }
                                }
                            }
                            else if (discount.equals(HotelEnum.RegionalLocation.AvailableRedPackets.getValue()) ||
                                    discount.equals(HotelEnum.RegionalLocation.AvailableCoupons.getValue())){//可用红包/可用券
                                count = 1;
                                if (ratePlan.getUsedPromotionValuesList() != null && ratePlan.getUsedPromotionValuesList().size() > 0){
                                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.UsedPromotionValues usedPromotionValues : ratePlan.getUsedPromotionValuesList()) {
                                        if (usedPromotionValues.getPromotionTypeId() == 10 ||
                                                usedPromotionValues.getPromotionTypeId() == 11 ||
                                                usedPromotionValues.getPromotionTypeId() == 62 ||
                                                usedPromotionValues.getPromotionTypeId() == 63){
                                            roomId.add(room.getRoomId());
                                        }
                                    }
                                }
                            }
                            else if (discount.equals(HotelEnum.RegionalLocation.StoreNewCustomers.getValue())){//门店新客
                                count = 1;
                                if (ratePlan.getDayPromotionsList() != null && ratePlan.getDayPromotionsList().size() > 0){
                                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.DayPromotions dayPromotions : ratePlan.getDayPromotionsList()) {
                                        if (dayPromotions.getPromotions() != null && dayPromotions.getPromotions().size() > 0){
                                            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.Promotions promotion : dayPromotions.getPromotions()) {
                                                if (promotion.getPromotionType() == 2){
                                                    roomId.add(room.getRoomId());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        LinkedHashSet<String> roomHashSet = new LinkedHashSet<>(roomId);
        ArrayList<String> roomlist = new ArrayList<>(roomHashSet);
        LinkedHashSet<String> valueAddHashSet = new LinkedHashSet<>(valueAddId);
        ArrayList<String> valueAddlist = new ArrayList<>(valueAddHashSet);
        LinkedHashSet<Long> prepayRuleHashSet = new LinkedHashSet<>(prepayRuleId);
        ArrayList<Long> prepayRulelist = new ArrayList<>(prepayRuleHashSet);

        HotelDetailOutput hotelDetail = roomsBeanList(roomlist, valueAddlist, prepayRulelist, hotelDetailOutput, count);

        for (HotelDetailResponse.HotelsBean hotel : hotelDetail.Result.getHotels()) {
            List<RoomList> roomLists = new ArrayList<>();
            for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                RoomList roomList = new RoomList();
                roomList.RoomId = room.getRoomId();
                roomList.LowRate = hotel.getLowRate();
                roomList.ImageUrl = room.getImageUrl();
                roomList.Name = room.getName();
                roomList.Description = room.getDescription();

                List<RoomRate> roomRates = new ArrayList<>();
                for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                    RoomRate roomRate = new RoomRate();
                    roomRate.RatePlanId = ratePlan.getRatePlanId();
                    roomRate.RoomTypeId = ratePlan.getRoomTypeId();
                    roomRate.TotalRate = ratePlan.getTotalRate();
                    roomRate.Coupon = ratePlan.getCoupon().toString();
                    roomRate.RatePlanName = ratePlan.getRatePlanName();
                    roomRate.mealCopyWriting = ratePlan.getMeals().getMealCopyWriting();
                    roomRate.PaymentType = ratePlan.getPaymentType();
                    for (String breakfast : roomTypeVo.getBreakfast()) {
                        if (breakfast.equals(HotelEnum.RegionalLocation.WithoutBreakfast.getValue())) {
                            if (ratePlan.getMeals().getMealCopyWriting().equals("无餐食"))
                                roomRates.add(roomRate);
                        } else {
                            if (!ratePlan.getMeals().getMealCopyWriting().equals("无餐食"))
                                roomRates.add(roomRate);
                        }
                    }

                }
                roomList.RoomRates = roomRates;
                roomLists.add(roomList);
            }

            hotelDetails.roomLists = roomLists;
        }

        return hotelDetails;
    }

    public HotelDetailOutput roomsBeanList(List<String> roomIdList, List<String> valueAddIdlist, List<Long> prepayRulelist,
                                             HotelDetailOutput hotelDetailOutput, int count){
        List<HotelDetailResponse.HotelsBean.ValueAdd> valueAddList = new ArrayList<>();
        List<HotelDetailResponse.HotelsBean.RoomsBean> roomsBeanList = new ArrayList<>();
        List<HotelDetailResponse.HotelsBean.PrepayRulesBean> prepayRulesBeans = new ArrayList<>();
        for (HotelDetailResponse.HotelsBean hotelHotel : hotelDetailOutput.Result.getHotels()) {
            if (valueAddIdlist != null && valueAddIdlist.size() > 0){
                for (String valueAddId : valueAddIdlist) {
                    for (HotelDetailResponse.HotelsBean.ValueAdd valueAdd : hotelHotel.getValueAdds()) {
                        if (valueAddId.equals(valueAdd.getValueAddId())){
                            valueAddList.add(valueAdd);
                        }
                    }
                }
            }

            if (roomIdList != null && roomIdList.size() > 0){
                for (String roomId : roomIdList) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean room : hotelHotel.getRooms()) {
                        if (roomId.equals(room.getRoomId())){
                            roomsBeanList.add(room);
                        }
                    }
                }
            }

            if (prepayRulelist != null && prepayRulelist.size() > 0){
                for (Long prepayRule : prepayRulelist) {
                    for (HotelDetailResponse.HotelsBean.PrepayRulesBean rule : hotelHotel.getPrepayRules()) {
                        if (prepayRule == rule.getPrepayRuleId()){
                            prepayRulesBeans.add(rule);
                        }
                    }
                }
            }

            LinkedHashSet<HotelDetailResponse.HotelsBean.PrepayRulesBean> prepayRuleHashSet = new LinkedHashSet<>(prepayRulesBeans);
            ArrayList<HotelDetailResponse.HotelsBean.PrepayRulesBean> prepayRules = new ArrayList<>(prepayRuleHashSet);
            hotelHotel.setPrepayRules(prepayRules);

            LinkedHashSet<HotelDetailResponse.HotelsBean.ValueAdd> valueAddHashSet = new LinkedHashSet<>(valueAddList);
            ArrayList<HotelDetailResponse.HotelsBean.ValueAdd> valueAddlist = new ArrayList<>(valueAddHashSet);
            hotelHotel.setValueAdds(valueAddlist);

            if (count == 1){
                LinkedHashSet<HotelDetailResponse.HotelsBean.RoomsBean> roomHashSet = new LinkedHashSet<>(roomsBeanList);
                ArrayList<HotelDetailResponse.HotelsBean.RoomsBean> roomlist = new ArrayList<>(roomHashSet);
                hotelHotel.setRooms(roomlist);
            }
        }
        return hotelDetailOutput;
    }

    /**
     * 酒店房型筛选赋值
     */
    public RoomList assign(HotelDetailResponse.HotelsBean.RoomsBean room){
        double lowRateMin = 0;
        RoomList rooms = new RoomList();
        rooms.RoomId = room.getRoomId();
        rooms.Name = room.getName();
        rooms.ImageUrl = room.getImageUrl();
        rooms.Description = room.getDescription();
        for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
            for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean.NightlyRatesBean nightlyRate : ratePlan.getNightlyRates()) {
                if (nightlyRate.isStatus() == true && ratePlan.getStatus() == true) {
                    RoomRate roomRate = new RoomRate();
                    roomRate.RatePlanId = ratePlan.getRatePlanId();
                    roomRate.RoomTypeId = ratePlan.getRoomTypeId();
                    roomRate.Coupon = ratePlan.getCoupon().toString();
                    roomRate.TotalRate = ratePlan.getTotalRate();
                    roomRate.RatePlanName = ratePlan.getRatePlanName();
                    roomRate.PaymentType = ratePlan.getPaymentType();
                    roomRate.mealCopyWriting = ratePlan.getMeals().getMealCopyWriting();
                    rooms.RoomRates.add(roomRate);
                }
            }
            //取到房型的所有价格放到一个集合中，然后取最底的价格返回出去
            List<Double> collect = rooms.RoomRates.stream().map(item ->
                    item.TotalRate.doubleValue()
            ).collect(Collectors.toList());
            Collections.sort(collect);
            lowRateMin = collect.get(0);
        }
        rooms.LowRate = lowRateMin;
        return rooms;
    }

    /**
     * 国内酒店-创建订单(艺龙下单)
     * @return
     */
    @Override
    public CreateOrderResult createOrder(String token, HttpServletRequest request, Long bankCardId, Long orderId, Long customerId, BankCard bankCard) throws Exception {
        HotelOrder hotelOrder = hotelOrderMapper.checkHotelReservations(orderId);
        List<HotelOrderRoom> hotelOrderRooms = hotelOrderRoomMapper.checkHotelReservationsDetails(orderId);
        CreateHotelOrder condition = new CreateHotelOrder();
        condition.ConfirmationType = "NoNeed";
        condition.CurrencyCode = "RMB";
        condition.useDeposit = false;
        condition.usePoint = false;
        condition.IsNeedInvoice = false;
        List<Guest> nameList = new ArrayList<>();
        for (HotelOrderRoom hotelOrderRoom : hotelOrderRooms) {
            Guest guest = new Guest();
            guest.name = hotelOrderRoom.getGuestname();
            nameList.add(guest);
        }
        for (HotelOrderRoom hotelOrderRoom : hotelOrderRooms) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            condition.ArrivalDate = dateFormat.format(hotelOrderRoom.getStarttime());
            condition.RoomTypeId = hotelOrderRoom.getRoomtypeid();
            condition.DepartureDate = dateFormat.format(hotelOrderRoom.getEndtime());
        }
        condition.Customers = nameList;
        condition.LatestArrivalTime = hotelOrder.getLatestArrivalTime();
        condition.EarliestArrivalTime = hotelOrder.getEarliestArrivalTime();
        condition.HotelId = hotelOrder.getHotelid();
        condition.Mobile = hotelOrder.getPhone();
        condition.NumberOfCustomers = nameList.size();
        condition.NumberOfRooms = hotelOrder.getNumberOfRooms();
        condition.orderType = hotelOrder.getOrdertype();

        condition.RatePlanId = Integer.parseInt(hotelOrder.getRatePlanId());
        condition.totalsalePrice = hotelOrder.getPayAmount();



        HotelDetailInput input = new HotelDetailInput();
        input.ArrivalDate = condition.ArrivalDate;
        input.DepartureDate = condition.DepartureDate;
        input.HotelIds = condition.HotelId;
        input.RoomTypeId = condition.RoomTypeId;
        HotelDetailOutput hotelDetail;
        try {
            hotelDetail = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        condition.Options = "1,2,3,4";
        condition.IsGuaranteeOrCharged = true;
        condition.IsCreateOrderOnly = false;
        CreateOrderResult result = new CreateOrderResult();
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        hotelDetailInput.ArrivalDate = condition.ArrivalDate;
        hotelDetailInput.DepartureDate = condition.DepartureDate;
        hotelDetailInput.HotelIds = condition.HotelId;
        hotelDetailInput.RoomTypeId = condition.RoomTypeId;
        hotelDetailInput.Options = condition.Options;
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        R<Customer> customer;
        if (customerId == 0){
            customer = remoteCustomerService.getLoginCustomerByToken(token);
        }
        else {
            customer = remoteCustomerService.getCustomerId(customerId);
        }

        if (customer.getCode() == 500){
            throw new Exception("登录已过期");
        }
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());

        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);

        HotelOrder hotelOrders;
        try {
            hotelOrders = assign(hotelDetailOutput, condition, customer.getData(), customerCardR);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

//        DataValidateVo dataValidateVo = new DataValidateVo();
//        dataValidateVo.setArrivalDate(condition.ArrivalDate);
//        dataValidateVo.setDepartureDate(condition.DepartureDate);
//        dataValidateVo.setEarliestArrivalTime(condition.EarliestArrivalTime);
//        dataValidateVo.setLatestArrivalTime(condition.LatestArrivalTime);
//        dataValidateVo.setHotelId(condition.HotelId);
//        dataValidateVo.setRoomTypeID(condition.RoomTypeId);
//        dataValidateVo.setRatePlanId(condition.RatePlanId);
//        dataValidateVo.setTotalPrice(condition.TotalPrice);
//        dataValidateVo.setNumberOfRooms(condition.NumberOfRooms);

        for (HotelDetailResponse.HotelsBean hotel : hotelDetail.Result.getHotels()) {
            for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                    if (ratePlan.getIsPromotion().equals("true")){//是否促销
                        condition.LittleMajiaId = ratePlan.getLittlemajiaid();
                        condition.GoodsUniqId = ratePlan.getGoodsUniqId();
                        condition.TotalPrice = ratePlan.getTotalRate();
                    }
                }
            }
        }

        // todo 测试期间数据验证关闭
//        HotelValidateOutPut validate;
//        try {
//            validate = validate(dataValidateVo);
//        } catch (Exception e){
//            throw new Exception(e.getMessage());
//        }
//
//        if (!validate.getCode().equals("0")){
//            throw new Exception("数据验证失败");
//        }
        long millis = System.currentTimeMillis();
        condition.AffiliateConfirmationId = String.valueOf(millis);
        condition.TotalPrice = condition.TotalPrice.multiply(new BigDecimal(condition.NumberOfCustomers));
        GetIPAddress getIPAddress = new GetIPAddress();
        if (request != null){
            String ipAddress = getIPAddress.getIPAddress(request);
            condition.CustomerIPAddress = ipAddress;
        }
        else {
            condition.CustomerIPAddress = "172.16.7.51";
        }
        CreateHotelOrderVo hotelOrderVo = createHotelOrderVo(condition);
        if (hotelOrders.getOrdertype() == 1){
            hotelOrderVo.PaymentType = "SelfPay";
        }
        else if (hotelOrders.getOrdertype() == 2){
            if (bankCardId != null && bankCardId != 0){
                hotelOrderVo = creditCard(hotelOrderVo, bankCardId, token, customerId, bankCard);
            }
            else {
                throw new Exception("该订单银行卡id不能为空");
            }
        }
        else if (hotelOrders.getOrdertype() == 3){
            hotelOrderVo.PaymentType = "Prepay";
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            hotelOrderVo.EarliestArrivalTime = format.format(format.parse(hotelOrderVo.ArrivalDate)) + " " + hotelOrderVo.EarliestArrivalTime;
            hotelOrderVo.LatestArrivalTime = format.format(format.parse(hotelOrderVo.ArrivalDate)) + " " + hotelOrderVo.LatestArrivalTime;
        } catch (Exception e){
            throw new Exception("最早到店时间或最晚到店时间有误");
        }

        result = (CreateOrderResult) getResult(result, hotelOrderVo, HotelUtils.HOTEL_ORDER_CREATE);

        if (result.Code.equals("0")) {
            hotelOrderMapper.updateELongOrderId(result.Result.getOrderId(), orderId);

            OrderIdCondition orderIdCondition = new OrderIdCondition();
            HotelOrder ho = new HotelOrder();
            orderIdCondition.setOrderId(result.Result.getOrderId());
            OrderDetailResult orderDetailResult = ElongUtils.orderDetail(orderIdCondition);
            ho.setOrderid(hotelOrders.getOrderid());
            ho.setSupplierorderid(result.Result.getOrderId().toString());
            ho.setCanceltime(result.Result.getCancelTime());
            ho.setShowstatus(orderDetailResult.Result.ShowStatus);
            ho.setStatus(orderDetailResult.Result.Status);
            hotelOrderMapper.updateHotelOrder(ho);
        }
        else {
            throw new Exception(result.Code);
        }
        return result;
    }

    /**
     * Crm艺龙创建订单
     * */
    @Override
    public CreateOrderResult bankCreateOrder(Long orderId, String backNum) throws Exception {
        HotelOrder hotelOrder = hotelOrderMapper.checkHotelReservations(orderId);
        List<HotelOrderRoom> hotelOrderRooms = hotelOrderRoomMapper.checkHotelReservationsDetails(orderId);
        CreateHotelOrder condition = new CreateHotelOrder();
        condition.ConfirmationType = "NoNeed";
        condition.CurrencyCode = "RMB";
        condition.useDeposit = false;
        condition.usePoint = false;
        condition.IsNeedInvoice = false;
        List<Guest> nameList = new ArrayList<>();
        for (HotelOrderRoom hotelOrderRoom : hotelOrderRooms) {
            Guest guest = new Guest();
            guest.name = hotelOrderRoom.getGuestname();
            nameList.add(guest);
        }
        for (HotelOrderRoom hotelOrderRoom : hotelOrderRooms) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            condition.ArrivalDate = dateFormat.format(hotelOrderRoom.getStarttime());
            condition.RoomTypeId = hotelOrderRoom.getRoomtypeid();
            condition.DepartureDate = dateFormat.format(hotelOrderRoom.getEndtime());
        }
        condition.Customers = nameList;
        condition.LatestArrivalTime = hotelOrder.getLatestArrivalTime();
        condition.EarliestArrivalTime = hotelOrder.getEarliestArrivalTime();
        condition.HotelId = hotelOrder.getHotelid();
        condition.Mobile = hotelOrder.getPhone();
        condition.NumberOfCustomers = nameList.size();
        condition.NumberOfRooms = hotelOrder.getNumberOfRooms();
        condition.orderType = hotelOrder.getOrdertype();

        condition.RatePlanId = Integer.parseInt(hotelOrder.getRatePlanId());
        condition.totalsalePrice = hotelOrder.getPayAmount();

        HotelDetailInput input = new HotelDetailInput();
        input.ArrivalDate = condition.ArrivalDate;
        input.DepartureDate = condition.DepartureDate;
        input.HotelIds = condition.HotelId;
        input.RoomTypeId = condition.RoomTypeId;
        HotelDetailOutput hotelDetail;
        try {
            hotelDetail = ElongUtils.queryByIdHotel(input);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        condition.Options = "1,2,3,4";
        condition.IsGuaranteeOrCharged = true;
        condition.IsCreateOrderOnly = false;
        CreateOrderResult result = new CreateOrderResult();
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        hotelDetailInput.ArrivalDate = condition.ArrivalDate;
        hotelDetailInput.DepartureDate = condition.DepartureDate;
        hotelDetailInput.HotelIds = condition.HotelId;
        hotelDetailInput.RoomTypeId = condition.RoomTypeId;
        hotelDetailInput.Options = condition.Options;
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        R<Customer> customer = remoteCustomerService.getCustomerId(hotelOrder.getCustomerid());

        if (customer.getCode() == 500){
            throw new Exception("登录已过期");
        }
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());

        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);

        HotelOrder hotelOrders;
        try {
            hotelOrders = assign(hotelDetailOutput, condition, customer.getData(), customerCardR);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

//        DataValidateVo dataValidateVo = new DataValidateVo();
//        dataValidateVo.setArrivalDate(condition.ArrivalDate);
//        dataValidateVo.setDepartureDate(condition.DepartureDate);
//        dataValidateVo.setEarliestArrivalTime(condition.EarliestArrivalTime);
//        dataValidateVo.setLatestArrivalTime(condition.LatestArrivalTime);
//        dataValidateVo.setHotelId(condition.HotelId);
//        dataValidateVo.setRoomTypeID(condition.RoomTypeId);
//        dataValidateVo.setRatePlanId(condition.RatePlanId);
//        dataValidateVo.setTotalPrice(condition.TotalPrice);
//        dataValidateVo.setNumberOfRooms(condition.NumberOfRooms);

        for (HotelDetailResponse.HotelsBean hotel : hotelDetail.Result.getHotels()) {
            for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                    if (ratePlan.getTotalRate().compareTo(hotelOrderRooms.get(0).getPriceunit()) == 0) {
                        condition.LittleMajiaId = ratePlan.getLittlemajiaid();
                        condition.GoodsUniqId = ratePlan.getGoodsUniqId();
                        condition.TotalPrice = ratePlan.getTotalRate();
                    }
                }
            }
        }

        // todo 测试期间数据验证关闭
//        HotelValidateOutPut validate;
//        try {
//            validate = validate(dataValidateVo);
//        } catch (Exception e){
//            throw new Exception(e.getMessage());
//        }
//
//        if (!validate.getCode().equals("0")){
//            throw new Exception("数据验证失败");
//        }
        long millis = System.currentTimeMillis();
        condition.AffiliateConfirmationId = String.valueOf(millis);
        condition.TotalPrice = condition.TotalPrice.multiply(new BigDecimal(condition.NumberOfCustomers));
        GetIPAddress getIPAddress = new GetIPAddress();
        condition.CustomerIPAddress = "172.16.7.51";
        CreateHotelOrderVo hotelOrderVo = createHotelOrderVo(condition);
        if (hotelOrders.getOrdertype() == 1){
            hotelOrderVo.PaymentType = "SelfPay";
        }
        else if (hotelOrders.getOrdertype() == 2){
            Map<String, Object> map = new HashMap<>();
            map.put("memberId", orderId);
            map.put("cardNumber", backNum);
            BankCard bankCard = remoteCustomerService.selectBackCardNum(map);
            if (bankCard != null){
                hotelOrderVo = creditCard(hotelOrderVo, null, null, hotelOrder.getCustomerid(), bankCard);
            }
            else {
                throw new Exception("该订单银行卡id不能为空");
            }
        }
        else if (hotelOrders.getOrdertype() == 3){
            hotelOrderVo.PaymentType = "Prepay";
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            hotelOrderVo.EarliestArrivalTime = format.format(format.parse(hotelOrderVo.ArrivalDate)) + " " + hotelOrderVo.EarliestArrivalTime;
            hotelOrderVo.LatestArrivalTime = format.format(format.parse(hotelOrderVo.ArrivalDate)) + " " + hotelOrderVo.LatestArrivalTime;
        } catch (Exception e){
            throw new Exception("最早到店时间或最晚到店时间有误");
        }

        result = (CreateOrderResult) getResult(result, hotelOrderVo, HotelUtils.HOTEL_ORDER_CREATE);

        if (result.Code.equals("0")) {
            hotelOrderMapper.updateELongOrderId(result.Result.getOrderId(), orderId);

            OrderIdCondition orderIdCondition = new OrderIdCondition();
            HotelOrder ho = new HotelOrder();
            orderIdCondition.setOrderId(result.Result.getOrderId());
            OrderDetailResult orderDetailResult = ElongUtils.orderDetail(orderIdCondition);
            ho.setOrderid(hotelOrders.getOrderid());
            ho.setSupplierorderid(result.Result.getOrderId().toString());
            ho.setCanceltime(result.Result.getCancelTime());
            ho.setShowstatus(orderDetailResult.Result.ShowStatus);
            ho.setStatus(orderDetailResult.Result.Status);
            hotelOrderMapper.updateHotelOrder(ho);
        }
        else {
            throw new Exception(result.Code);
        }
        return result;
    }

    /**
     * 艺龙下单担保信用卡信息
     * */
    public CreateHotelOrderVo creditCard(CreateHotelOrderVo hotelOrderVo, Long bankCardId, String token, Long customerId, BankCard bankCard) throws Exception {
        Customer customer;
        if (customerId == 0){
            customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
        }
        else {
            customer = remoteCustomerService.getCustomerId(customerId).getData();
        }

        String idType = customer.getIdType();
        String custCertificateNo = customer.getCustCertificateNo();
        if (custCertificateNo == null || custCertificateNo.equals("")){
            throw new Exception("证件号不能为空");
        }

//        if (bankCardId != null && bankCardId != 0){
//            bankCard = remoteCustomerService.selectBankCardBytBankCardId(bankCardId);
//        }

        if (bankCard.getCardType().equals("creditcard")){
            String timeStamp=String.valueOf(new Date().getTime()/1000);
            // todo 测试卡号
            bankCard.setCardNumber("4336660000000000");
//            bankCard.setCardNumber(bankCard.getCardNumber());

            String password = HotelUtils.ELONG_PREPAY_APPKEY.substring(HotelUtils.ELONG_PREPAY_APPKEY.length()-8);
            CreditCard creditCard = new CreditCard();
            creditCard.ExpirationYear = Integer.parseInt(bankCard.getCreditCardTime().substring(0, 4));
            creditCard.ExpirationMonth = Integer.parseInt(bankCard.getCreditCardTime().substring(5, 7));
            creditCard.HolderName = CipherUtil.desEncrypt(timeStamp + "#" + bankCard.getCardholder(), password);;
            creditCard.IdNo = CipherUtil.desEncrypt(timeStamp + "#" + custCertificateNo, password);
            creditCard.IdType = idType;
            creditCard.Number = CipherUtil.desEncrypt(timeStamp + "#" + bankCard.getCardNumber(), password);
            creditCard.CVV = CipherUtil.desEncrypt(timeStamp + "#" + bankCard.getCvv2(), password);
            creditCard.Mobile = CipherUtil.desEncrypt(timeStamp + "#" + bankCard.getObligatePhone(), password);

            hotelOrderVo.CreditCard = creditCard;
        }
        else {
            throw new Exception("该银行卡不是信用卡");
        }
        return hotelOrderVo;
    }

    public CreateHotelOrderVo createHotelOrderVo(CreateHotelOrder condition){
        CreateHotelOrderVo createHotelOrderVo = new CreateHotelOrderVo();
        createHotelOrderVo.AffiliateConfirmationId = condition.AffiliateConfirmationId;
        createHotelOrderVo.orderType = condition.orderType;
        createHotelOrderVo.HotelId = condition.HotelId;
        createHotelOrderVo.RoomTypeId = condition.RoomTypeId;
        createHotelOrderVo.RatePlanId = condition.RatePlanId;
        createHotelOrderVo.ArrivalDate = condition.ArrivalDate;
        createHotelOrderVo.DepartureDate = condition.DepartureDate;
        createHotelOrderVo.PaymentType = condition.PaymentType;
        createHotelOrderVo.NumberOfRooms = condition.NumberOfRooms;
        createHotelOrderVo.NumberOfCustomers = condition.NumberOfCustomers;
        createHotelOrderVo.EarliestArrivalTime = condition.EarliestArrivalTime;
        createHotelOrderVo.LatestArrivalTime = condition.LatestArrivalTime;
        createHotelOrderVo.CurrencyCode = condition.CurrencyCode;
        createHotelOrderVo.TotalPrice = condition.TotalPrice;
        createHotelOrderVo.CustomerIPAddress = condition.CustomerIPAddress;
        createHotelOrderVo.ConfirmationType = condition.ConfirmationType;
        createHotelOrderVo.IsNeedInvoice = condition.IsNeedInvoice;
        List<CustomerVo> Customers = new ArrayList<>();
        for (Guest customers : condition.Customers) {
            CustomerVo customer = new CustomerVo();
            customer.Name = customers.name;
//            customer.Nationality = "中国";
            Customers.add(customer);
        }
        List<OrderRoom> orderRooms = new ArrayList<>();
        OrderRoom orderRoom = new OrderRoom();
        orderRoom.Customers = Customers;
        orderRooms.add(orderRoom);
        createHotelOrderVo.orderRooms = orderRooms;
        ContactVo contact = new ContactVo();
        contact.Name = condition.Customers.get(0).name;
        contact.Mobile = condition.Mobile;
//        contact.Gender = "Female";
        createHotelOrderVo.Contact = contact;
        createHotelOrderVo.IsCreateOrderOnly = condition.IsCreateOrderOnly;
        createHotelOrderVo.IsGuaranteeOrCharged = condition.IsGuaranteeOrCharged;
        createHotelOrderVo.payAmount = condition.payAmount;
        createHotelOrderVo.Options = condition.Options;
        createHotelOrderVo.HotelName = condition.HotelName;
        createHotelOrderVo.Name = condition.Name;
        createHotelOrderVo.passengerId = condition.passengerId;
        createHotelOrderVo.points = condition.points;
        createHotelOrderVo.couponId = condition.couponId;
        createHotelOrderVo.totalsalePrice = condition.totalsalePrice;
        createHotelOrderVo.basePrice = condition.basePrice;
        createHotelOrderVo.usedDeposit = condition.usedDeposit;
        createHotelOrderVo.productId = condition.productId;
        if (condition.productamount != null && condition.productamount.size() > 0)
            createHotelOrderVo.productamount.addAll(condition.productamount);
        createHotelOrderVo.ShopperProductId = condition.ShopperProductId;
        createHotelOrderVo.SubSupplierId = condition.SubSupplierId;
        createHotelOrderVo.SupplierId = condition.SupplierId;
        createHotelOrderVo.HotelCode = condition.HotelCode;
        createHotelOrderVo.NumberOfAdults = condition.NumberOfAdults;
        createHotelOrderVo.LittleMajiaId = condition.LittleMajiaId;
        createHotelOrderVo.GoodsUniqId = condition.GoodsUniqId;
        createHotelOrderVo.useDeposit = condition.useDeposit;
        createHotelOrderVo.usePoint = condition.usePoint;

        return createHotelOrderVo;
    }

    public CreateHotelOrder createHotelOrder(HotelDetailOutput hotelDetail, CreateHotelOrder createHotelOrder, String token, Long customerId){
//        if (createHotelOrder.productId != null && createHotelOrder.productId.size() > 0){
//            for (Integer productId : createHotelOrder.productId) {
//                //辅营产品
//                Map<String, Object> map = new HashMap<>();
//                map.put("status", AssistProductEnum.activation.getValue());
//                map.put("businessType", AssistProductEnum.hotel.getValue());
//                map.put("id", productId);
//                AssistProductVoApi assistProductVo = remoteCustomerService.assistProduct(map);
//                createHotelOrder.productamount.add(assistProductVo);
//            }
//        }
//        else {
//            createHotelOrder.productamount = null;
//        }

        if (hotelDetail != null) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetail.Result.getHotels()) {
                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                    for (HotelDetailResponse.HotelsBean.RoomsBean.RatePlansBean ratePlan : room.getRatePlans()) {
                        if (ratePlan.getRoomTypeId().equals(createHotelOrder.RoomTypeId) &&
                                ratePlan.getRatePlanId() == createHotelOrder.RatePlanId){
                            createHotelOrder.TotalPrice = ratePlan.getTotalRate();
                        }
                    }
                }
                for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                    createHotelOrder.HotelName = detailBean.getHotelName();
                    createHotelOrder.address = detailBean.getAddress();
                    createHotelOrder.phone = detailBean.getPhone();
                }
            }
        }

        //金币
        R<Long> depositBusinessByToken;
        //会员id等于0，则为前台app访问,token获取数据
        if (customerId == null || customerId == 0){
            depositBusinessByToken = remoteCustomerService.queyUserDepositBusinessByToken(token);
        }
        //会员id不等于0，则为后台crm访问,会员id获取数据
        else {
            depositBusinessByToken = remoteCustomerService.selectAvailableGoldByCustomerId(customerId);
        }

        if (depositBusinessByToken.getData() != null){
            createHotelOrder.usedDeposit = new BigDecimal(depositBusinessByToken.getData());
        }

        //积分
        R<Long> points;
        if (customerId == null || customerId == 0){
            points = remoteCustomerService.queyUserCreditsNumByToken(token);
        }
        else {
            points = remoteCustomerService.queyUserCreditsNumByCustomerId(customerId);
        }

        if (points.getData() != null) {
            createHotelOrder.points = points.getData();
        }
        return createHotelOrder;
    }


    /**
     * 酒店支付
     * */
    @Override
    public Map<String, Object> hotelPays(Long orderNumber, String openId, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        HotelOrder reservations = hotelOrderMapper.checkHotelReservations(orderNumber);

        if (amount.compareTo(new BigDecimal(0)) > 0){
            reservations.setPayAmount(reservations.getPayAmount().subtract(amount));

            reservations.setDepositAmount(amount);
            int i = hotelOrderMapper.updateHotelOrder(reservations);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("酒店微信小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.HOTEL.getValue());
            depositBusiness.setOperatorId(1l);
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(reservations.getCustomerid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(orderNumber);
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "酒店微信小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        String notifyUrl = "/hotel/callback/hotelWechatPayCallback";
        R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, reservations.getPayAmount(), orderNumber.toString(), notifyUrl);
        if (wechatJSAPIPayParam.getCode() == 200) {
            List<HotelOrderAssist> hotelOrderAssists = hotelOrderAssistMapper.selectHotelOrderAssistListByOrderId(reservations.getOrderid());
            if (hotelOrderAssists != null && hotelOrderAssists.size() > 0)
                hotelOrderAssist(reservations, hotelOrderAssists);
            return wechatJSAPIPayParam.getData();
        }

        HotelOrderException hotelOrderException = new HotelOrderException();

        List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(orderNumber.toString());
        if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
            String person = null;
            for (int i = 0; i < hotelOrderRoomList.size(); i++) {
                if (i == 0){
                    person = hotelOrderRoomList.get(i).getGuestname();
                }
                else {
                    person = person + "|" + hotelOrderRoomList.get(i).getGuestname();
                }
            }
            hotelOrderException.setPerson(person);
        }
        hotelOrderException.setPersonPhone(reservations.getPhone());
        hotelOrderException.setHotelName(reservations.getHotelname());
        hotelOrderException.setReserveTime(reservations.getCreateTime());
        hotelOrderException.setExceptionInfo("支付失败");
        hotelOrderException.setSourceWay("App");
        hotelOrderException.setStatus("processed");
        hotelOrderException.setOrderId(reservations.getOrderid().toString());
        hotelOrderException.setOrderType("reserve");
        hotelOrderException.setEmployeeId(10l);
        hotelOrderException.setCustomerId(reservations.getCustomerid());
        hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);

//        FinanceOrderRefundment refundment = new FinanceOrderRefundment();
//        refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.hotel.getValue()));
//        refundment.setCustomerId(reservations.getCustomerid());
//        refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
//        refundment.setRefundmentAmount(reservations.getPayAmount());
//        refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
//        refundment.setOrderId(String.valueOf(reservations.getOrderid()));
//        refundment.setApplyTime(new Date());
//        if (order.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
//            refundment.setPaymentTypeId("2");
//        } else if (order.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
//            refundment.setPaymentTypeId("1");
//        }
//        remoteCustomerService.add(refundment);
        return null;
    }

    /**
     * 辅营产品处理
     * @param hotelOrder
     * @param hotelOrderAssists
     */
    private void hotelOrderAssist(HotelOrder hotelOrder, List<HotelOrderAssist> hotelOrderAssists) {
        for (HotelOrderAssist hotelOrderAssist : hotelOrderAssists) {
            R<AssistProductApi> assistProductApiR = remoteCustomerService.queryAssistProduct(hotelOrderAssist.getAssistProductId());
            if (assistProductApiR.getCode() == 200 && assistProductApiR.getData() != null) {
                if (assistProductApiR.getData().getProductType().equals("conpon")) {
                    R<Coupon> couponR = remoteCustomerService.couponById(assistProductApiR.getData().getProductTypeid());
                    CustomerRightdetail customerRightdetai = new CustomerRightdetail();
                    customerRightdetai.setCustomerId(hotelOrder.getCustomerid());
                    customerRightdetai.setRightdetailId(couponR.getData().getCouponId());
                    customerRightdetai.setRightdetailName(couponR.getData().getCouponName());
                    customerRightdetai.setCouponMoney(couponR.getData().getCouponPrice());
                    customerRightdetai.setValidDate(new Date());
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.YEAR, 1);
                    customerRightdetai.setInvalidDate(calendar.getTime());
                    customerRightdetai.setCreateEmployeeId(1L);
                    customerRightdetai.setCreateTime(new Date());
                    customerRightdetai.setRightdetailSource(CustomerConstants.rightSourcePack.getValue());
                    customerRightdetai.setRightdetailType(CustomerConstants.rightTypeCoupon.getValue());
                    customerRightdetai.setRightdetailTypeid(couponR.getData().getCouponId());
                    customerRightdetai.setRightdetailState(CustomerConstants.unexecuted.getValue());
                    remoteCustomerService.addCustomerRightdetail(customerRightdetai);
                }
            }
        }
    }

    /**
     * 酒店收银台
     * @param token
     * @param orderId
     * @return
     */
    @Override
    public HotelCashier payOrder(String token, Long orderId, HttpServletRequest request) throws Exception {
        HotelCashier hotelCashier = new HotelCashier();
        R<Customer> loginCustomerByToken = remoteCustomerService.getLoginCustomerByToken(token);
        if (loginCustomerByToken.getData() == null){
            throw new Exception("登录已过期，请重新登录");
        }
        Customer data = loginCustomerByToken.getData();
        Long customerId = data.getCustomerId();
        Long expireTime = redisService.redisTemplate.getExpire(HOTEL + customerId + ORDER + orderId);
        HotelOrderPayInfo hotelOrderPayInfo = hotelOrderMapper.queryHotelOrderPayInfo(orderId);
        hotelCashier.setOrderStatusID(hotelOrderPayInfo.getOrderStatusID());
        hotelCashier.setHotelName(hotelOrderPayInfo.getHotelName());
        hotelCashier.setArriveTime(hotelOrderPayInfo.getArriveTime());
        hotelCashier.setCheckOutTime(hotelOrderPayInfo.getCheckOutTime());
        hotelCashier.setRoomTypeName(hotelOrderPayInfo.getRoomTypeName());
        hotelCashier.setNumberOfRooms(hotelOrderPayInfo.getNumberOfRooms());
        hotelCashier.setCheckInTime(hotelOrderPayInfo.getCheckInTime());
        hotelCashier.setPayAmount(hotelOrderPayInfo.getPayAmount());
        if (expireTime != null && expireTime > 0) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("businessType", AssistProductEnum.hotel.getValue());
            List<PayTypeApi> payTypes = payService.queryPayType(AssistProductEnum.hotel.getValue());
            if (payTypes != null && payTypes.size() > 0){
                for (PayTypeApi payType : payTypes) {
                    PayTypeVo payTypeVo = new PayTypeVo();
                    payTypeVo.setPayId(payType.getPayId());
                    payTypeVo.setPayName(payType.getPayName());
                    payTypeVo.setPayType(payType.getPayType());
                    payTypeVo.setPayInfo(payType.getPayInfo());

                    if (payType.getPayType().equals("BankCard")){
                        List<BankCardVo> bankCardList = new ArrayList<>();

                        Map<String, Object> memberId = new HashMap<>();
                        memberId.put("memberId", customerId);
                        List<BankCard> bankCards = remoteCustomerService.selectBankCardByMemberId(memberId);
                        if (bankCards != null && bankCards.size() > 0){
                            for (BankCard bankCard : bankCards) {
                                BankCardVo bankCardVo = new BankCardVo();
                                bankCardVo.setBankCardId(bankCard.getBankCardId());
                                bankCardVo.setCardNumber(bankCard.getCardNumber().substring(bankCard.getCardNumber().length() - 4));
                                bankCardVo.setBankName(bankCard.getBankName());
                                bankCardVo.setBankLogoName(bankCard.bankLogoName);
                                bankCardList.add(bankCardVo);
                            }
                        }

                        payTypeVo.setBankCardList(bankCardList);
                    }

                    hotelCashier.getPayType().add(payTypeVo);
                }
            }
            else {
                throw new Exception("未查到支付方式");
            }
            hotelCashier.setExpiredTime(String.valueOf(expireTime));
        } else {
            hotelCashier.setExpiredTime("订单已超时");
        }

        return hotelCashier;
    }

    /**
     * 国内酒店-订单列表
     * @param
     * @return
     */
    @Override
    public OrderList orderList(String token, String type) throws Exception {
        OrderList orderLists = new OrderList();
        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        Long customerId = customer.getData().getCustomerId();
        HotelOrderVo hotelOrderVo = new HotelOrderVo();
        hotelOrderVo.setCustomerId(customerId);
        if (type != null){
            if (type.equals("pay")){//待支付
                hotelOrderVo.setOrderstatusid(1l);
            }
            else if (type.equals("check")){//待入住
                hotelOrderVo.setIsused("false");
            }
        }
        List<HotelOrder> hotelOrders = hotelOrderMapper.queryByCustomerIdOrderList(hotelOrderVo.getCustomerId(), hotelOrderVo.getOrderstatusid(), hotelOrderVo.getIsused());
        List<OrderVo> orderVoList;
        try {
            orderVoList = orderVoList(hotelOrders, customerId);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        Integer count = hotelOrderMapper.queryByIdCount(customerId);
        orderLists.setCount(count);
        orderLists.setOrderVoList(orderVoList);
        return orderLists;
    }

    public List<OrderVo> orderVoList(List<HotelOrder> hotelOrders, Long customerId) throws Exception {
        List<OrderVo> orderVoList = new ArrayList<>();

        if (hotelOrders != null && hotelOrders.size() > 0){
            for (HotelOrder order : hotelOrders) {
                for (HotelOrderRoom hotelOrderRoom : order.getHotelOrderRoom()) {
                    OrderVo orderVo = new OrderVo();
                    orderVo.setOrderId(order.getOrderid());
                    orderVo.setHotelName(order.getHotelname());
                    orderVo.setOrderStatusID(order.getOrderstatusid());
                    orderVo.setPic_path(hotelOrderRoom.getPicPath());
                    orderVo.setNumberOfRooms(order.getNumberOfRooms());
                    orderVo.setArriveTime(order.getArrivetime());
                    orderVo.setCheckOutTime(order.getCheckouttime());
                    orderVo.setRoomTypeName(hotelOrderRoom.getRoomTypeName());
                    orderVo.setActualPriceTotal(order.getPayAmount());
                    orderVo.setOrderType(orderType(order.getOrdertype()));
                    if (order.getOrderstatusid() == 1){
                        Long expireTime = redisService.redisTemplate.getExpire(HOTEL + customerId + ORDER + order.getOrderid());
                        if (expireTime != null && expireTime > 0) {
                            orderVo.setTimeOut("false");
                            orderVo.setRemainingTime(String.valueOf(expireTime));
                        } else {
                            orderVo.setTimeOut("true");
                        }
                    }
                    orderVoList.add(orderVo);
                }
            }
        }
        return orderVoList;
    }

    public String orderType(Long orderType){
        String orderName = "";
        if (orderType == 3){
            orderName = HotelEnum.RegionalLocation.OnlinePayment.getValue();
        }
        return orderName;
    }

    /**
     * 国内酒店-取消订单（接口）
     * @param condition
     * @return
     */
    @Override
    public CancelOrderResult cancelOrder(CancelOrderCondition condition) {
        if (condition.getCancelCode() == null || condition.getCancelCode().equals("")){
            condition.setCancelCode("其他");
        }

        CancelOrderResult result = new CancelOrderResult();
        OrderIdCondition orderIdCondition = new OrderIdCondition();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        try {
//            String orderId = hotelMapper.selectOrderId(condition.getOrderId());
//            if (orderId != null) {
            orderIdCondition.setOrderId(condition.getOrderId());
//                orderIdCondition.setAffiliateConfirmationId("0");
            OrderDetailResult orderDetailResult = ElongUtils.orderDetail(orderIdCondition);
            HotelOrder hotelOrder = new HotelOrder();
            CancelOrder Result = new CancelOrder();
            if (orderDetailResult.Code.equals("0")) {
                String newNumber = orderDetailResult.Result.CancelTime.replace("T", " ");
                Date parse = simpleDateFormat.parse(newNumber);
                hotelOrder.setELongOrderId(condition.getOrderId());
                if (orderDetailResult.Result.IsCancelable == true && parse.getTime() > simpleDateFormat.parse(format).getTime()) {
                    condition.setOrderId(condition.getOrderId());
                    condition.setPenaltyAmount(orderDetailResult.Result.PenaltyToCustomer);
                    result = (CancelOrderResult) getResult(result, condition, HotelUtils.HOTEL_ORDER_CANCEL);
                }
                else if (orderDetailResult.Result.IsCancelable == false){
                    hotelOrder.setMsg("当前酒店不可取消");
                    hotelOrderMapper.updateMsg(hotelOrder);
                    Result.Successs = false;
                    Result.msg = "当前酒店不可取消";
                    result.Code = "-1";
                    result.Result = Result;
                }
                else if (parse.getTime() < simpleDateFormat.parse(format).getTime()){
                    hotelOrder.setMsg("当前时间大于取消时间");
                    hotelOrderMapper.updateMsg(hotelOrder);
                    Result.Successs = false;
                    result.Code = "-1";
                    Result.msg = "当前时间大于取消时间";
                    result.Result = Result;
                }
            } else
            {
                hotelOrder.setMsg(orderDetailResult.Code);
                hotelOrderMapper.updateMsg(hotelOrder);
                Result.Successs = false;
                Result.msg = orderDetailResult.Code;
                result.Code = "-1";
                result.Result = Result;
            }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 国内酒店-订单取消（退款）
     * */
    @Override
    public CancelOrderResult hotelOrderCancel(CancelOrderCondition condition, HttpServletRequest request) throws Exception {
//        boolean b=false;
//        try {
//            b = cancelStart(condition.getOrderId());
//        } catch (Exception e){
//            throw new Exception(e.getMessage());
//        }

//        CancelOrderResult cancelOrderResult = cancelOrder(condition);
//        if (cancelOrderResult != null && !cancelOrderResult.Result.Successs){
//            throw new Exception(cancelOrderResult.Result.msg);
//        }

        Date date = new Date();
        HotelOrder hotelOrder = hotelOrderMapper.selectHotelOrderByELongOrderNum(condition.getOrderId().toString());
        if (hotelOrder == null){
            throw new Exception("无效的订单号");
        }
        HotelOrderPaydetail hotelOrderPaydetail = hotelOrderPaydetailMapper.orderDetailsByOrderid(Long.valueOf(hotelOrder.getOrderNum()));


        String token = request.getHeader("token");
        R<Employee> loginEmployeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken.getData() == null){
            throw new Exception("登陆已过期");
        }

        CancelOrderResult cancelOrderResult = cancelOrder(condition);
        if (cancelOrderResult.Code.equals("-1"))
        {
            return cancelOrderResult;
        }
        if (!cancelOrderResult.Code.equals("0")){

            HotelOrderException hotelOrderException = new HotelOrderException();

            List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
            if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
                String person = null;
                for (int n = 0; n < hotelOrderRoomList.size(); n++) {
                    if (n == 0){
                        person = hotelOrderRoomList.get(n).getGuestname();
                    }
                    else {
                        person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
                    }
                }
                hotelOrderException.setPerson(person);
            }
            hotelOrderException.setPersonPhone(hotelOrder.getPhone());
            hotelOrderException.setHotelName(hotelOrder.getHotelname());
            hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
            hotelOrderException.setExceptionInfo("艺龙取消订单失败");
            hotelOrderException.setSourceWay("App");
            hotelOrderException.setStatus("processed");
            hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
            hotelOrderException.setOrderType("reserve");
            hotelOrderException.setEmployeeId(10l);
            hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);

            throw new Exception("取消订单失败");
        }
        if (condition.getRemark() != null && !condition.getRemark().equals("")){
            condition.setOrderNum(Long.valueOf(hotelOrder.getOrderNum()));
            int i = hotelOrderPaydetailMapper.updateRemark(condition);
            if (i <= 0){
                throw new Exception("添加备注失败");
            }
        }

//        boolean flag = false;
//        //退款
//        //原路返回
//        if (condition.getRefundMethod() != null && Integer.parseInt(condition.getRefundMethod()) == com.ktgj.common.core.constant.FinanceOrderRefundment.backtrack.getValue()){
//            //信用卡
//            if (hotelOrderPaydetail.getPaytype().equals(BusinessTypeConstants.BankCredit.getValue())){
//                Map<String, String> map = new HashMap<>();
//                map.put("jsjOrderId", hotelOrder.getOrderNum());
//                map.put("bankTrxId", hotelOrderPaydetail.getHmac());
//                map.put("moneyAmout", condition.getRefundAmount());
//                map.put("payType", condition.getPayWay());
//                YeeBaoResultApi yeeBaoResultApi = remotePayService.bankCreditRefund(map);
//                if (yeeBaoResultApi.getCode().equals("1")){
//                    flag = true;
//                    if (hotelOrder.getDepositAmount() != null && hotelOrder.getDepositAmount().compareTo(new BigDecimal(0)) > 0){
//                        CancelOrderCondition tmpCondition = new CancelOrderCondition();
//                        tmpCondition.setRefundAmount(hotelOrder.getDepositAmount().toString());
//                        tmpCondition.setPayWay(condition.getPayWay());
//                        int i = reserveMoney(loginEmployeeByToken, condition, hotelOrder);
//                        if (i <= 0){
//                            flag = false;
//
//                            HotelOrderException hotelOrderException = new HotelOrderException();
//
//                            List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                            if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                                String person = null;
//                                for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                                    if (n == 0){
//                                        person = hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                    else {
//                                        person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                }
//                                hotelOrderException.setPerson(person);
//                            }
//                            hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                            hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                            hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                            hotelOrderException.setExceptionInfo("退款失败");
//                            hotelOrderException.setSourceWay("App");
//                            hotelOrderException.setStatus("processed");
//                            hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                            hotelOrderException.setOrderType("reserve");
//                            hotelOrderException.setEmployeeId(10l);
//                            hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                            throw new Exception("预留款退款失败");
//                        }
//                    }
//                }
//                else {
//
//                    HotelOrderException hotelOrderException = new HotelOrderException();
//
//                    List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                    if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                        String person = null;
//                        for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                            if (n == 0){
//                                person = hotelOrderRoomList.get(n).getGuestname();
//                            }
//                            else {
//                                person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                            }
//                        }
//                        hotelOrderException.setPerson(person);
//                    }
//                    hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                    hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                    hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                    hotelOrderException.setExceptionInfo("退款失败");
//                    hotelOrderException.setSourceWay("App");
//                    hotelOrderException.setStatus("processed");
//                    hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                    hotelOrderException.setOrderType("reserve");
//                    hotelOrderException.setEmployeeId(10l);
//                    hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                    throw new Exception(yeeBaoResultApi.getErrorMsg());
//                }
//            }
//            //借记卡
//            else if (hotelOrderPaydetail.getPaytype().equals(BusinessTypeConstants.BankDebit.getValue())){
//                Map<String, String> map = new HashMap<>();
//                map.put("jsjOrderId", hotelOrder.getOrderNum());
//                map.put("bankTrxId", hotelOrderPaydetail.getHmac());
//                map.put("moneyAmout", condition.getRefundAmount());
//                YeeBaoResultApi yeeBaoResultApi = remotePayService.bankDebitRefund(map);
//                if (yeeBaoResultApi.getCode().equals("1")){
//                    flag = true;
//                    if (hotelOrder.getDepositAmount() != null && hotelOrder.getDepositAmount().compareTo(new BigDecimal(0)) > 0){
//                        CancelOrderCondition tmpCondition = new CancelOrderCondition();
//                        tmpCondition.setRefundAmount(hotelOrder.getDepositAmount().toString());
//                        tmpCondition.setPayWay(condition.getPayWay());
//                        int i = reserveMoney(loginEmployeeByToken, condition, hotelOrder);
//                        if (i <= 0){
//                            flag = false;
//
//                            HotelOrderException hotelOrderException = new HotelOrderException();
//
//                            List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                            if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                                String person = null;
//                                for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                                    if (n == 0){
//                                        person = hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                    else {
//                                        person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                }
//                                hotelOrderException.setPerson(person);
//                            }
//                            hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                            hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                            hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                            hotelOrderException.setExceptionInfo("退款失败");
//                            hotelOrderException.setSourceWay("App");
//                            hotelOrderException.setStatus("processed");
//                            hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                            hotelOrderException.setOrderType("reserve");
//                            hotelOrderException.setEmployeeId(10l);
//                            hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                            throw new Exception("预留款退款失败");
//                        }
//                    }
//                }
//                else {
//
//                    HotelOrderException hotelOrderException = new HotelOrderException();
//
//                    List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                    if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                        String person = null;
//                        for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                            if (n == 0){
//                                person = hotelOrderRoomList.get(n).getGuestname();
//                            }
//                            else {
//                                person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                            }
//                        }
//                        hotelOrderException.setPerson(person);
//                    }
//                    hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                    hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                    hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                    hotelOrderException.setExceptionInfo("退款失败");
//                    hotelOrderException.setSourceWay("App");
//                    hotelOrderException.setStatus("processed");
//                    hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                    hotelOrderException.setOrderType("reserve");
//                    hotelOrderException.setEmployeeId(10l);
//                    hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                    throw new Exception(yeeBaoResultApi.getErrorMsg());
//                }
//            }
//            //银联二维码
//            else if (hotelOrderPaydetail.getPaytype().equals(BusinessTypeConstants.UnionQRCodePay.getValue())){
//                Map<String, String> map = new HashMap<>();
//                map.put("refundAmount", condition.getRefundAmount());
//                map.put("billNo", hotelOrderPaydetail.getHmac());
//                map.put("notifyUrl", "http://106.38.39.137:8080/hotel/callback/retreatUnionPayQRCallback");
//                UnionPayQRCodeResponseApi unionPayQRCodeResponseApi = remotePayService.qrCodeRefund(map);
//                if (unionPayQRCodeResponseApi.getErrCode().equals("SUCCESS")){
//                    flag = true;
//                    if (hotelOrder.getDepositAmount() != null && hotelOrder.getDepositAmount().compareTo(new BigDecimal(0)) > 0){
//                        CancelOrderCondition tmpCondition = new CancelOrderCondition();
//                        tmpCondition.setRefundAmount(hotelOrder.getDepositAmount().toString());
//                        tmpCondition.setPayWay(condition.getPayWay());
//                        int i = reserveMoney(loginEmployeeByToken, condition, hotelOrder);
//                        if (i <= 0){
//                            flag = false;
//
//                            HotelOrderException hotelOrderException = new HotelOrderException();
//
//                            List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                            if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                                String person = null;
//                                for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                                    if (n == 0){
//                                        person = hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                    else {
//                                        person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                                    }
//                                }
//                                hotelOrderException.setPerson(person);
//                            }
//                            hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                            hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                            hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                            hotelOrderException.setExceptionInfo("退款失败");
//                            hotelOrderException.setSourceWay("App");
//                            hotelOrderException.setStatus("processed");
//                            hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                            hotelOrderException.setOrderType("reserve");
//                            hotelOrderException.setEmployeeId(10l);
//                            hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                            throw new Exception("预留款退款失败");
//                        }
//                    }
//                }
//                else {
//
//                    HotelOrderException hotelOrderException = new HotelOrderException();
//
//                    List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                    if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                        String person = null;
//                        for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                            if (n == 0){
//                                person = hotelOrderRoomList.get(n).getGuestname();
//                            }
//                            else {
//                                person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                            }
//                        }
//                        hotelOrderException.setPerson(person);
//                    }
//                    hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                    hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                    hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                    hotelOrderException.setExceptionInfo("退款失败");
//                    hotelOrderException.setSourceWay("App");
//                    hotelOrderException.setStatus("processed");
//                    hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                    hotelOrderException.setOrderType("reserve");
//                    hotelOrderException.setEmployeeId(10l);
//                    hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                    throw new Exception(unionPayQRCodeResponseApi.getErrMsg());
//                }
//            }
//        }
//        //预留款
//        else if (condition.getRefundMethod() != null && Integer.parseInt(condition.getRefundMethod()) == com.ktgj.common.core.constant.FinanceOrderRefundment.reserveMoney.getValue()){
//            int i = reserveMoney(loginEmployeeByToken, condition, hotelOrder);
//            if (i <= 0){
//
//                HotelOrderException hotelOrderException = new HotelOrderException();
//
//                List<HotelOrderRoom> hotelOrderRoomList = hotelOrderRoomMapper.selectHotelOrderRoomByOrderNum(hotelOrder.getOrderNum());
//                if (hotelOrderRoomList != null && hotelOrderRoomList.size() > 0){
//                    String person = null;
//                    for (int n = 0; n < hotelOrderRoomList.size(); n++) {
//                        if (n == 0){
//                            person = hotelOrderRoomList.get(n).getGuestname();
//                        }
//                        else {
//                            person = person + "|" + hotelOrderRoomList.get(n).getGuestname();
//                        }
//                    }
//                    hotelOrderException.setPerson(person);
//                }
//                hotelOrderException.setPersonPhone(hotelOrder.getPhone());
//                hotelOrderException.setHotelName(hotelOrder.getHotelname());
//                hotelOrderException.setReserveTime(hotelOrder.getCreateTime());
//                hotelOrderException.setExceptionInfo("退款失败");
//                hotelOrderException.setSourceWay("App");
//                hotelOrderException.setStatus("processed");
//                hotelOrderException.setOrderId(hotelOrder.getOrderid().toString());
//                hotelOrderException.setOrderType("reserve");
//                hotelOrderException.setEmployeeId(10l);
//                hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
//
//                throw new Exception("预留款退款失败");
//            }
//        }
//        //人工退款
//        else if (condition.getRefundMethod() != null && Integer.parseInt(condition.getRefundMethod()) == com.ktgj.common.core.constant.FinanceOrderRefundment.manualRefund.getValue()){
//
//        }

        FinanceOrderRefundment refundment = new FinanceOrderRefundment();
        refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.hotel.getValue()));
        refundment.setCustomerId(hotelOrder.getCustomerid());
        if (condition.getRefundMethod() != null){
            if (condition.getRefundMethod().equals(FlightOrderConstants.backtrack.getValue())){
                refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.backtrack.getValue()));
            }
            else if (condition.getRefundMethod().equals(FlightOrderConstants.reserveMoney.getValue())){
                refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.reserveMoney.getValue()));
            }
            else {
                refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.manualRefund.getValue()));
            }
        }

        refundment.setRefundmentAmount(new BigDecimal(condition.getRefundAmount())); //TODO 测试，手续费暂为0，后期完善
        refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
        refundment.setOrderId(hotelOrder.getOrderid().toString());
        refundment.setApplyTime(date);
        if (hotelOrderPaydetail.getPaytype().equals("1")) {
            refundment.setPaymentTypeId("2");
        } else if (hotelOrderPaydetail.getPaytype().equals("6")) {
            refundment.setPaymentTypeId("1");
        }
        refundment.setSerialnumber(hotelOrder.getSerial());
        int save = remoteCustomerService.save(refundment);
        if (save <= 0){
            throw new Exception("会员退款信息添加失败");
        }
        HotelOrderRefundapply hotelOrderRefundapply = new HotelOrderRefundapply();
        hotelOrderRefundapply.setOrderid(Long.valueOf(hotelOrder.getOrderNum()));
        hotelOrderRefundapply.setSupplierid(Long.valueOf(hotelOrder.getELongOrderId()));
        hotelOrderRefundapply.setRefundamount(condition.getPenaltyAmount());
        hotelOrderRefundapply.setRefundstatus(1l);
        int i = hotelOrderRefundapplyMapper.insertHotelOrderRefundapply(hotelOrderRefundapply);
        if (i <= 0){
            throw new Exception("酒店退订添加失败");
        }
        return null;
//        return cancelOrderResult;
    }


    /**
     * 国内酒店-删除订单
     * @param removeOrder
     * @return
     */
    @Override
    public int deleteOrder(RemoveOrder removeOrder) {
        return hotelMapper.deleteOrder(removeOrder);
    }

    /**
     * 预留款退款
     * */
    public int reserveMoney(R<Employee> loginEmployeeByToken, CancelOrderCondition condition, HotelOrder hotelOrder) {
        DepositBusinessApi depositBusinessApi = new DepositBusinessApi();
        depositBusinessApi.setOperationtime(new Date());
        depositBusinessApi.setRemark("酒店退款");
        depositBusinessApi.setState("notReviewed");
        depositBusinessApi.setBusinessType(EmHelper.businessType.HOTEL.getValue());
        depositBusinessApi.setOperatorId(loginEmployeeByToken.getData().getEmployeeId());
        depositBusinessApi.setOrdersourceid(condition.getPayWay());
        depositBusinessApi.setCustomerId(hotelOrder.getCustomerid());
        depositBusinessApi.setDetailamount(new BigDecimal(condition.getRefundAmount()));
        depositBusinessApi.setChangetype(1l);
        depositBusinessApi.setOperapersonid(loginEmployeeByToken.getData().getEmployeeId());
        depositBusinessApi.setOrderId(Long.valueOf(hotelOrder.getOrderNum()));
        Long aLong = remoteCustomerService.addReserveMoney(depositBusinessApi);
        if (aLong > 0){
            return 1;
        }
        else {
            return 0;
        }
    }

    /**
     * 获取艺龙接口酒店列表数据
     * */
    @Override
    public TotalVo dataStitching(HotelInput hotelInput) throws Exception
    {
        if (hotelInput != null && !hotelInput.equals(""))
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            //艺龙接口参数赋值
            ConditionVo conditionVo = new ConditionVo();

            String cityName;
            try
            {
                cityName = cityName(hotelInput);
            } catch (Exception e)
            {
                throw new Exception(e.getMessage());
            }

            Date enterTime;
            Date leaveTime;
            Date date;
            try
            {
                enterTime = format.parse(hotelInput.getArrivalDate());
                leaveTime = format.parse(hotelInput.getDepartureDate());
                date = format.parse(format.format(new Date()));
            } catch (Exception e)
            {
                throw new Exception("日期转换错误");
            }

            if (date.compareTo(enterTime) > 0)
            {
                throw new Exception("入住时间不能小于当前时间");
            } else
            {
                if (enterTime.compareTo(leaveTime) > 0)
                {
                    throw new Exception("离店时间不能小于入住时间");
                }
            }

            try
            {
                conditionVo.setArrivalDate(hotelInput.getArrivalDate());
                conditionVo.setDepartureDate(hotelInput.getDepartureDate());
                conditionVo.setCityName(cityName);
                if (!StringHelper.isNullOrEmpty(hotelInput.getKeywords()))
                {
                    conditionVo.setQueryText(hotelInput.getKeywords());
                }
            } catch (Exception e)
            {
                throw new Exception("缺少必要参数");
            }

            //拼接艺龙接口非必填参数
            ConditionVo condition = condition(conditionVo, hotelInput);

            HotelDetailOutput hotelDetailOutput;
            hotelDetailOutput = queryByIdHotelList(condition);
            if (hotelDetailOutput == null)
            {
                throw new Exception("城市信息为空！");
            }

            List<HotelVo> hotelVoList;
            HotelDetailOutput match;
            List<HotelsVo> hotelsVoList;
            List<HotelsVo> hotelsVos;
            try
            {
                hotelVoList = HotelList(hotelInput, hotelDetailOutput);
                match = match(hotelVoList, hotelDetailOutput);
                hotelsVoList = hotelOutputList(hotelVoList, hotelInput, match);
                hotelsVos = hotelsVoListSorting(hotelsVoList, hotelInput.getSorting());
            } catch (Exception e)
            {
                throw new Exception(e.getMessage());
            }

            TotalVo totalVo = new TotalVo();
            totalVo.setTotalNumber(hotelDetailOutput.Result.getCount());

            /** todo 测试酒店数据 */
            HotelDetailInput input = new HotelDetailInput();
            input.ArrivalDate = hotelInput.getArrivalDate();
            input.DepartureDate = hotelInput.getDepartureDate();
            input.HotelIds = "10101129";
            HotelDetailOutput hotelDetailOutput1 = ElongUtils.queryByIdHotel(input);
            TemporaryHotelVo temporaryHotelVo = new TemporaryHotelVo();
            List<Long> hotelId = new ArrayList<>();
            hotelId.add(10101129l);
            temporaryHotelVo.setProvinceName("兴城");
            temporaryHotelVo.setHotelId(hotelId);

            List<HotelVo> hotelVoList1 = hotelMapper.selectHotelsList(temporaryHotelVo);

            List<HotelsVo> hotelsVoList1 = hotelOutputList(hotelVoList1, hotelInput, hotelDetailOutput1);
            for (HotelsVo hotelsVo : hotelsVoList1)
            {
                hotelsVos.get(0).setId(hotelsVo.getId());
                hotelsVos.get(0).setPicPath(hotelsVo.getPicPath());
                hotelsVos.get(0).setHotelName(hotelsVo.getHotelName());
                hotelsVos.get(0).setCommentScore(hotelsVo.getCommentScore());
                hotelsVos.get(0).setDistance(hotelsVo.getDistance());
                hotelsVos.get(0).setCommentCount(hotelsVo.getCommentCount());
                hotelsVos.get(0).setNearLandmark(hotelsVo.getNearLandmark());
                hotelsVos.get(0).setStarName(hotelsVo.getStarName());
                hotelsVos.get(0).setActivelabelName(hotelsVo.getActivelabelName());
                hotelsVos.get(0).setBaseMinPrice(new BigDecimal(hotelsVo.getBaseMinPrice().setScale(0, BigDecimal.ROUND_UP).longValue()));
                hotelsVos.get(0).setSales(hotelsVo.getSales());
                hotelsVos.get(0).setLowRate(Math.ceil(hotelsVo.getLowRate()));
            }

            totalVo.setHotelsVoList(hotelsVos);

            return totalVo;
        } else
        {
            throw new Exception("参数不能为空");
        }
    }

    /**
     * 条件查询酒店列表(自营)
     * */
    @Override
    public TotalVo stitching(HotelInput hotelInput) throws Exception {
        if (hotelInput != null && !hotelInput.equals("")) {

            TotalVo totalVo = new TotalVo();

            List<Hotels> hotels = hotelMapper.hotels(hotelInput);
            totalVo.setTotalNumber(hotels.size());
            if (hotels != null && hotels.size() > 0){
                List<HotelsVo> hotelsVoList = new ArrayList<>();

                if (hotels.size() >= ((hotelInput.getPageNum() - 1) * hotelInput.getPageSize())){
                    for (int i = ((hotelInput.getPageNum() - 1) * hotelInput.getPageSize()) ; i < hotels.size() ; i++) {
                        HotelsVo hotelsVo = new HotelsVo();
                        hotelsVo.setId(hotels.get(i).getId().toString());
                        hotelsVo.setHotelName(hotels.get(i).getHotelName());

                        if (hotels.get(i).getStarId() != null){
                            DicStars dicStars = dicStarsMapper.selectDicStarsById(hotels.get(i).getStarId());
                            if (dicStars != null){
                                hotelsVo.setStarName(dicStars.getStarsName());
                            }
                        }

                        if (hotels.get(i).getIsValid() != null){
                            if (hotels.get(i).getIsValid() == 1){
                                hotelsVo.setHotelStart("已签约");
                            }
                            else {
                                hotelsVo.setHotelStart("未签约");
                            }
                        }
                        else {
                            hotelsVo.setHotelStart("未签约");
                        }

                        hotelsVo.setHotelLevel(hotels.get(i).getRecommendLevel().toString());
                        hotelsVoList.add(hotelsVo);

                        if (hotelsVoList.size() == hotelInput.getPageSize()){
                            break;
                        }
                    }
                }

                totalVo.setHotelsVoList(hotelsVoList);
            }

            return totalVo;
        }
        else {
            throw new Exception("参数不能为空");
        }
    }

    /**
     * 拼接艺龙接口参数
     * */
    public ConditionVo condition(ConditionVo conditionVo, HotelInput hotelInput) throws Exception {
        //页码
        if (hotelInput.getPageNum() > 0) {
            conditionVo.setPageIndex(hotelInput.getPageNum());
        } else {
            conditionVo.setPageIndex(1);//页码默认为1
        }

        //每页显示数据量
        if (hotelInput.getPageSize() > 0 && hotelInput.getPageSize() <= 20) {
            conditionVo.setPageSize(hotelInput.getPageSize());
        } else {
            conditionVo.setPageSize(20);
        }


        //查询关键字（酒店名称）
        if (hotelInput.getHotelName() != null && !hotelInput.getHotelName().equals("")) {
            conditionVo.setQueryText(hotelInput.getHotelName());
        }
        //查询关键字（地址）
        else if (hotelInput.getAddress() != null && !hotelInput.getAddress().equals("")) {
            conditionVo.setQueryText(hotelInput.getAddress());
        } else if (hotelInput.getKeywords() != null && !hotelInput.getKeywords().equals("")) {
            conditionVo.setQueryText(hotelInput.getKeywords());
        }

        //价格
        if (hotelInput.getMinPrice() != null && !hotelInput.getMinPrice().equals("") &&
                hotelInput.getMaxPrice() != null && !hotelInput.getMaxPrice().equals("") &&
                !hotelInput.getMinPrice().equals("0") && !hotelInput.getMaxPrice().equals("0")) {
            int lowRate;
            int highRate;
            try {
                lowRate = Integer.parseInt(hotelInput.getMinPrice());
                highRate = Integer.parseInt(hotelInput.getMaxPrice());
            } catch (Exception e) {
                throw new Exception("价格填写有误");
            }
            if (highRate >= lowRate) {
                conditionVo.setLowRate(lowRate);
                conditionVo.setHighRate(highRate);
            } else {
                throw new Exception("最高价格不能小于最低价格");
            }
        }
        return conditionVo;
    }

    /**
     * 如果参数中未传入当前城市名称，则调用方法查询用户当前坐标的所在城市
     * */
    public String cityName(HotelInput hotelInput) throws Exception {
        if (hotelInput.getProvinceName() == null || hotelInput.getProvinceName().equals("")){//城市名称为空
            if (hotelInput.getLng() != null && !hotelInput.getLng().equals("") &&
                    hotelInput.getLat() != null && !hotelInput.getLat().equals("")){//经纬度不为空
                GaoDeUtil gaoDeUtil = new GaoDeUtil();
                String cityName = gaoDeUtil.cityName(hotelInput.getLng(), hotelInput.getLat());
                return cityName.substring(0, cityName.length()-1);
            }
            else {
                throw new Exception("经纬度不能为空");
            }
        }
        else {
            return hotelInput.getProvinceName();
        }
    }

    /**
     * 根据艺龙接口酒店id获取数据库酒店id列表
     * */
    public List<Long> hotelId(HotelDetailOutput hotelDetailOutput) throws Exception {
        List<Long> hotelIdList = new ArrayList<>();
        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            List<HotelSupplierLink> hotelSupplierLinkList = hotelSupplierLinkMapper.selectHotelSupplierLinkByHotelCode(hotel.getHotelId());
            if (hotelSupplierLinkList != null && hotelSupplierLinkList.size() > 0){
                List<Long> count = new ArrayList<>();
                for (HotelSupplierLink hotelSupplierLink : hotelSupplierLinkList) {
                    long millisecond;
                    try {
                        millisecond = millisecond(hotelSupplierLink.getCreateTime());
                    } catch (Exception e){
                        throw new Exception(e.getMessage());
                    }

                    count.add(millisecond);
                }
                count.sort((x, y) -> Double.compare(y, x));
                hotelIdList.add(hotelSupplierLinkList.get(0).getHotelId());
            }
        }

        return hotelIdList;
    }

    public long millisecond(Date date) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(format.parse(format.format(date)));
        } catch (Exception e){
            throw new Exception("日期转换错误");
        }
        return calendar.getTimeInMillis();
    }

    /**
     * 补全数据库查询酒店信息所需参数
     * */
    public TemporaryHotelVo temporaryHotelVo(HotelInput hotelInput, HotelDetailOutput hotelDetailOutput) throws Exception {
        LatitudeUtil latitudeUtil = new LatitudeUtil();
        TemporaryHotelVo temporaryHotelVo = new TemporaryHotelVo();
        String cityName;
        try {
            cityName = cityName(hotelInput);
            temporaryHotelVo.setProvinceName(cityName);//城市名称
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        //评分
        if (hotelInput.getScore() != null && !hotelInput.getScore().equals("") &&
                !hotelInput.getScore().equals("0") && !hotelInput.getScore().equals("999")){
            DicReviews dicReviews = dicReviewsMapper.selectDicReviewsById(Long.valueOf(hotelInput.getScore()));

            String score = (dicReviews.getReviewsName() / 10) + "." + (dicReviews.getReviewsName() % 10);

            temporaryHotelVo.setScore(Double.valueOf(score));
        }

        //评论数量
        if (hotelInput.getQuantity() != null && !hotelInput.getQuantity().equals("") &&
                !hotelInput.getQuantity().equals("0") && !hotelInput.getQuantity().equals("999")){
            DicReviews dicReviews = dicReviewsMapper.selectDicReviewsById(Long.valueOf(hotelInput.getQuantity()));
            temporaryHotelVo.setQuantity(Long.valueOf(dicReviews.getReviewsName()));
        }

        //早餐
        if (hotelInput.getBreakfast() != null && !hotelInput.getBreakfast().equals("") &&
                !hotelInput.getBreakfast().equals("0") && !hotelInput.getBreakfast().equals("999")){
            temporaryHotelVo.setBreakfast(Long.valueOf(hotelInput.getBreakfast()));
        }

        //房型
        if (hotelInput.getRoomType() != null && !hotelInput.getRoomType().equals("") &&
                !hotelInput.getRoomType().equals("0") && !hotelInput.getRoomType().equals("999")){
            temporaryHotelVo.setRoomType(hotelInput.getRoomType());
        }

        //酒店类型
        if (hotelInput.getHotelType() != null && hotelInput.getHotelType().size() > 0){
            for (String hotelType : hotelInput.getHotelType()) {
                if (hotelType != null && !hotelType.equals("") &&
                        !hotelType.equals("0") && !hotelType.equals("999")){
                    temporaryHotelVo.setHotelType(hotelInput.getHotelType());
                }
            }
        }

        //特色主题
        if (hotelInput.getFeaturedTopics() != null && hotelInput.getFeaturedTopics().size() > 0){
            List<String> temporaryFeaturedTopics = new ArrayList<>();

            for (String featuredTopic : hotelInput.getFeaturedTopics()) {
                String themsName = dicThemsMapper.themsName(Long.valueOf(featuredTopic));
                temporaryFeaturedTopics.add(featuredTopic);
                if (themsName != null && !themsName.equals("")){
                    temporaryFeaturedTopics.add("'"+themsName+"'");
                }
            }
            temporaryHotelVo.setFeaturedTopics(temporaryFeaturedTopics);
        }

        //服务设施
        if (hotelInput.getServiceFacilitiesList() != null &&hotelInput.getServiceFacilitiesList().size() > 0){
            for (String serviceFacilities : hotelInput.getServiceFacilitiesList()) {
                if (!serviceFacilities.equals("999")){
                    List<Long> temporaryServiceFacilitiesList = new ArrayList<>();

                    for (String temporaryService : hotelInput.getServiceFacilitiesList()) {
                        if (!temporaryService.equals("999") && !temporaryService.equals("0")){
                            temporaryServiceFacilitiesList.add(Long.valueOf(temporaryService));
                        }
                    }
                    temporaryHotelVo.setServiceFacilitiesList(temporaryServiceFacilitiesList);
                }
            }
        }

        //星级
        if (hotelInput.getStarRatingList() != null && hotelInput.getStarRatingList().size() > 0){
            List<String> temporaryStarRatingList = new ArrayList<>();

            for (String temporaryStar : hotelInput.getStarRatingList()) {
                if (temporaryStar != null && !temporaryStar.equals("0")){
                    temporaryStarRatingList.add(temporaryStar);
                    int temporary = Integer.parseInt(temporaryStar);
                    if (temporary != 7){
                        temporaryStarRatingList.add(String.valueOf(temporary+1));
                    }
                }
            }
            temporaryHotelVo.setStarRatingList(temporaryStarRatingList);
        }

        double lng = 0;
        double lat = 0;
        double distance = 0;

        if (hotelInput.getAddressId() != null && !hotelInput.getAddressId().equals("") &&
                !hotelInput.getAddressId().equals("0") && !hotelInput.getAddressId().equals("999") &&
                hotelInput.getAddressType() != null && !hotelInput.getAddressType().equals("")){

            if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.distance)){//距离
                DicDistance dicDistance = dicDistanceMapper.selectDicDistanceById(Long.valueOf(hotelInput.getAddressId()));
                if (dicDistance != null && !dicDistance.equals("")){
                    lng = Double.valueOf(hotelInput.getLng());
                    lat = Double.valueOf(hotelInput.getLat());
                    distance = dicDistance.getDistanceName();
                }
                else {
                    distance = 4000;
                }
            }

            if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.administrativeDistrict)){//行政区
                temporaryHotelVo.setAdministrativeDistrictId(Long.valueOf(hotelInput.getAddressId()));
            }
            else if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.airportStation)){//机场车站
                DicAirportStation dicAirportStation = dicAirportStationMapper.dicAirportStationLonAndLat(Long.valueOf(hotelInput.getAddressId()));
                if (dicAirportStation != null && !dicAirportStation.equals("")){
                    lng = dicAirportStation.getGoogleLon();
                    lat = dicAirportStation.getGoogleLat();
                }
            }
            else if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.businessDistrict)){//商圈
                temporaryHotelVo.setAdministrativeDistrictId(Long.valueOf(hotelInput.getAddressId()));
            }
            else if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.hospital)){//医院
                DicLankMark dicLankMark = dicLankMarkMapper.lngAndLat(Long.valueOf(hotelInput.getAddressId()));
                if (dicLankMark != null && !dicLankMark.equals("")){
                    lng = dicLankMark.getGoogleLon();
                    lat = dicLankMark.getGoogleLat();
                }
            }
            else if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.popularArea)){//热门区域
                DicHotPosition dicHotPosition = dicHotPositionMapper.lngAndLat(Long.valueOf(hotelInput.getAddressId()));
                if (dicHotPosition != null && !dicHotPosition.equals("")){
                    lng = dicHotPosition.getGoogleLon();
                    lat = dicHotPosition.getGoogleLat();
                }
            }
            else if (hotelInput.getAddressType().equals(HotelEnum.RegionalLocation.subwayStation)){//地铁站
                DicSubwayStation dicSubwayStation = dicSubwayStationMapper.dicSubwayStationLonAndLat(Long.valueOf(hotelInput.getAddressId()));
                if (dicSubwayStation != null && !dicSubwayStation.equals("")){
                    lng = dicSubwayStation.getGoogleLon();
                    lat = dicSubwayStation.getGoogleLat();
                }
            }
        }

        if (lng != 0 && lat != 0 && distance != 0){
            Map<String, Double> around = latitudeUtil.getAround(lng, lat, distance);
            temporaryHotelVo.setMinLng(around.get("minLng"));//最小经度
            temporaryHotelVo.setMinLat(around.get("minLat"));//最小纬度
            temporaryHotelVo.setMaxLng(around.get("maxLng"));//最大经度
            temporaryHotelVo.setMaxLat(around.get("maxLat"));//最大纬度
        }

        List<Long> hotelIdList = hotelId(hotelDetailOutput);
        temporaryHotelVo.setHotelId(hotelIdList);

        return temporaryHotelVo;
    }

    /**
     * 酒店艺龙条件查询酒店列表
     */
    public List<HotelVo> HotelList(HotelInput hotelInput, HotelDetailOutput hotelDetailOutput) throws Exception {
        TemporaryHotelVo temporaryHotelVo;

        //前端：拆分筛选条件集合中的条件（小程序跳过此步骤）
        if (hotelInput.getFilterVoList() != null && hotelInput.getFilterVoList().size() > 0){
            hotelInput = hotelInput(hotelInput);
        }

        try {
            temporaryHotelVo = temporaryHotelVo(hotelInput, hotelDetailOutput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        List<HotelVo> hotelVos = hotelMapper.selectHotelsList(temporaryHotelVo);
        if (hotelVos != null && hotelVos.size() > 0){
            return hotelVos;
        }
        else {
            throw new Exception("未查到酒店数据");
        }
    }

    /**
     * 拆分筛选条件集合
     * */
    public HotelInput hotelInput(HotelInput hotelInput){
        for (FilterVo filterVo : hotelInput.getFilterVoList()) {
            //服务设施
            if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.serviceFacilities.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.getServiceFacilitiesList().add(filterId);
                }
            }
            //酒店类型
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.hotelType.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.getHotelType().add(filterId);
                }
            }
            //特色主题
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.featuredTopics.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.getFeaturedTopics().add(filterId);
                }
            }
            //房型
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.roomType.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.setRoomType(filterId);
                }
            }
            //早餐
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.breakfast.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.setBreakfast(filterId);
                }
            }
            //评分
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.score.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.setScore(filterId);
                }
            }
            //评论数量
            else if (filterVo.getFilterType().equals(HotelEnum.RegionalLocation.commentsNum.getValue())){
                for (String filterId : filterVo.getFilterId()) {
                    hotelInput.setQuantity(filterId);
                }
            }
        }
        return hotelInput;
    }

    /**
     * 数据库酒店信息与艺龙酒店信息匹对
     * */
    public HotelDetailOutput match(List<HotelVo> hotelVoList, HotelDetailOutput hotelDetailOutput){
        HotelDetailOutput hotelDetail = new HotelDetailOutput();
        HotelDetailResponse response = new HotelDetailResponse();
        List<HotelDetailResponse.HotelsBean> hotelsBeanList = new ArrayList<>();
        for (HotelVo hotelVo : hotelVoList) {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
                if (hotelVo.getHotelSupplierLink().getHotelCode().equals(hotel.getHotelId())){
                    HotelDetailResponse.HotelsBean hotelsBean = hotel;
                    hotelsBeanList.add(hotelsBean);
                }
            }
        }
        response.setHotels(hotelsBeanList);
        hotelDetail.Result = response;
        return hotelDetail;
    }

    /**
     * 筛选所需字段
     * */
    public List<HotelsVo> hotelOutputList(List<HotelVo> list, HotelInput hotelInput, HotelDetailOutput hotelDetailOutput) throws Exception {
        List<HotelsVo> hotelsVoList = new ArrayList<>();
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            HotelsVo hotelsVo = new HotelsVo();
            hotelsVo.setId(hotel.getHotelId());
            for (HotelDetailResponse.HotelsBean.DetailBean detailBean : hotel.getDetail()) {
                Double meter = null;
                if (hotelInput.getLogo() == 0){
                    meter = gaoDeUtil.distanceMeter(hotelInput.getLng(), hotelInput.getLat(),
                            detailBean.getLongitude(), detailBean.getLatitude()) / 1000;
                    hotelsVo.setLng(detailBean.getLongitude());
                    hotelsVo.setLat(detailBean.getLatitude());
                }
                else if (hotelInput.getLogo() == 1){
                    String lng;
                    String lat;

                    DicAirportcityLink dicAirportcityLink = dicAirportcityLinkMapper.selectLngAndLat("%" + hotelInput.getKeywords() + "%");
                    DicAirportStation dicAirportStation = dicAirportStationMapper.selectLngAndLat("%" + hotelInput.getKeywords() + "%");
                    HotelVo hotelVo = hotelMapper.selectLngAndLat("%" + hotelInput.getKeywords() + "%");
                    if (dicAirportcityLink != null){
                        lng = dicAirportcityLink.getGoogleLon().toString();
                        lat = dicAirportcityLink.getGoogleLat().toString();
                    }
                    else if (dicAirportStation != null){
                        lng = String.valueOf(dicAirportStation.getGoogleLon());
                        lat = String.valueOf(dicAirportStation.getGoogleLat());
                    }
                    else if (hotelsVo != null){
                        lng = hotelVo.getGoogleLon().toString();
                        lat = hotelVo.getGoogleLat().toString();
                    }
                    else {
                        throw new Exception("未查到关键词数据");
                    }

                    int lngNum = lng.substring(lng.indexOf(".") + 1).length();
                    int latNum = lat.substring(lat.indexOf(".") + 1).length();

                    if (lngNum > 6){
                        lng = lng.substring(lng.indexOf(".") + 1, lng.indexOf(".") + 8);
                    }
                    if (latNum > 6){
                        lat = lat.substring(lat.indexOf(".") + 1, lat.indexOf(".") + 8);
                    }

                    meter = gaoDeUtil.distanceMeter(lng, lat, detailBean.getLongitude(), detailBean.getLatitude()) / 1000;
                }

                BigDecimal bigDecimal = new BigDecimal(meter);
                Double distance = bigDecimal.setScale(1, bigDecimal.ROUND_CEILING).doubleValue();
                hotelsVo.setDistance(distance);
                hotelsVo.setAddress(detailBean.getAddress());
                hotelsVo.setLowRate(Math.ceil(hotel.getLowRate()));
                for (HotelVo hotelVo : list) {
                    if (hotelVo.getHotelSupplierLink().getHotelCode().equals(hotel.getHotelId())){
                        if (hotelVo.getCommentScore() != null && hotelVo.getCommentScore().compareTo(new BigDecimal(0)) != 0){
                            hotelsVo.setCommentScore(hotelVo.getCommentScore());
                        }
                        else {
                            hotelsVo.setCommentScore(new BigDecimal(0));
                        }
                        hotelsVo.setNearLandmark(hotelVo.getNearLandmark());
                        hotelsVo.setStarName(hotelVo.getStarName());
                        hotelsVo.setActivelabelName(hotelVo.getActivelabelName());
                    }
                }
                hotelsVo.setPicPath(detailBean.getThumbNailUrl());
                hotelsVo.setHotelName(detailBean.getHotelName());
                hotelsVo.setBaseMinPrice(new BigDecimal(String.valueOf(Math.ceil(hotel.getLowRate()))));
                for (HotelDetailResponse.HotelsBean.DetailBean.ReviewBean reviewBean : detailBean.getReview()) {
                    hotelsVo.setCommentCount(reviewBean.getCount());
                }
            }
            hotelsVoList.add(hotelsVo);
        }
        return hotelsVoList;
    }

    /**
     * 酒店信息排序
     * */
    public List<HotelsVo> hotelsVoListSorting(List<HotelsVo> hotelsVoList, String sorting) {

        int count = 0;

        if (sorting == null || sorting.equals("")){
            sorting = "distance";
        }

        if (sorting.equals("distance")){//距离近到远
            hotelsVoList.sort((x, y) -> Double.compare(x.getDistance(), y.getDistance()));
            count = 1;
        }
        else if (sorting.equals("priceMin")){//价格低到高
            hotelsVoList.sort((x, y) -> Double.compare(x.getBaseMinPrice().doubleValue(), y.getBaseMinPrice().doubleValue()));
            count = 1;
        }
        else if (sorting.equals("priceMax")){//价格高到低
            hotelsVoList.sort((x, y) -> Double.compare(y.getBaseMinPrice().doubleValue(), x.getBaseMinPrice().doubleValue()));
            count = 1;
        }
        else if (sorting.equals("wordOfMouth")){//口碑高到低
            hotelsVoList.sort((x, y) -> Double.compare(y.getCommentScore().doubleValue(), x.getCommentScore().doubleValue()));
            count = 1;
        }
        else if (sorting.equals("salesMax")){//销量高到低

            for (HotelsVo hotelsVo : hotelsVoList) {
                Long salesNumber = hotelOrderMapper.salesNumber(Long.valueOf(hotelsVo.getId()));
                hotelsVo.setSales(salesNumber);
            }

            hotelsVoList.sort((x, y) -> Double.compare(y.getSales().doubleValue(), x.getSales().doubleValue()));
            count = 1;
        }
        else if (sorting.equals("praiseMax")){//好评高到低
            hotelsVoList.sort((x, y) -> Double.compare(y.getCommentScore().doubleValue(), x.getCommentScore().doubleValue()));
            count = 1;
        }
        else if (sorting.equals("reviews")){//点评数多到少
            hotelsVoList.sort((x, y) -> Double.compare(y.getCommentCount(), x.getCommentCount()));
            count = 1;
        }
        else if (sorting.equals("intelligent")){//智能排序

        }
        else if (sorting.equals("comprehensive")){//综合排序

        }
        if (count == 0){//如果因为参数传入错误导致没有排序，则默认走距离由近到远排序
            hotelsVoList.sort((x, y) -> Double.compare(x.getDistance(), y.getDistance()));
        }

        return hotelsVoList;
    }

    /**
     * 订单明细 todo 消费总额立减
     * */
    @Override
    public Map<String, Object> orderDetails(Long orderid, Long orderNum) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<OrderDetailsVo> orderDetailsVoList = new ArrayList<>();
        OrderDetailsVo orderDetailsVo = new OrderDetailsVo();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        HotelOrder hotelOrder;
        List<HotelOrderRoom> hotelOrderRoom;
        HotelOrderInvoice hotelOrderInvoice;
        HotelOrderPaydetail hotelOrderPaydetail;
//            HotelSupplierLink hotelSupplierLink;
        HotelVo hotelVo;

        try {
            if (orderNum != null && orderNum != 0){
                hotelOrder = hotelOrderMapper.detailsOrder(orderNum);
//                orderid = hotelOrder.getOrderid();
            }
            else {
                hotelOrder = hotelOrderMapper.orderDetails(orderid);
            }
            hotelOrderRoom = hotelOrderRoomMapper.orderDetails(Long.valueOf(hotelOrder.getOrderNum()));
//            hotelOrderInvoice = hotelOrderInvoiceMapper.orderDetails(hotelOrder.getCustomerid());
            hotelOrderPaydetail = hotelOrderPaydetailMapper.orderDetails(Long.valueOf(hotelOrder.getOrderNum()));
//                hotelSupplierLink = hotelSupplierLinkMapper.orderDetails(hotelOrder.getHotelid());
            hotelVo = hotelMapper.orderDetails(Long.valueOf(hotelOrder.getHotelid()));
        } catch (Exception e){
            return null;
        }

        for (HotelOrderRoom room : hotelOrderRoom) {
            orderDetailsVo.setOrderStatusId(orderStatus(hotelOrder.getOrderstatusid()));
            orderDetailsVo.setActualPriceTotal(room.getActualpricetotal().toString());
            orderDetailsVo.setHotelName(hotelOrder.getHotelname());
            orderDetailsVo.setHotelAddress(hotelOrder.getHoteladdress());
            orderDetailsVo.setHotelPhone(hotelOrder.getHotelphone());
            orderDetailsVo.setCheckInTime(hotelOrder.getCheckInTime());
            if (hotelVo != null){
                orderDetailsVo.setCommentScore(hotelVo.getCommentScore());
            }
            orderDetailsVo.setRoomTypeName(room.getRoomTypeName());
            if (hotelOrder.getNumberOfRooms() != null){
                orderDetailsVo.setNumberOfRooms(Long.valueOf(hotelOrder.getNumberOfRooms()));
            }
            if (hotelOrder.getCreateTime() != null){
                orderDetailsVo.setPlaceAnOrderTime(format.format(hotelOrder.getCreateTime()));
            }

            orderDetailsVo.setGuestName(room.getGuestname());
            orderDetailsVo.setRoomID(room.getRoomid());

            if (room.getCreateTime() != null){
                orderDetailsVo.setToPayTime(format.format(room.getCreateTime()));
            }

            orderDetailsVo.setPayType(hotelOrderPaydetail.getPaytype());
            orderDetailsVo.setBreakfastDesc(room.getBreakfastdesc());
//            orderDetailsVo.setInvoiceTitle(hotelOrderInvoice.getInvoicetitle());
            orderDetailsVoList.add(orderDetailsVo);
        }
        map.put("hotelOrderDetails", orderDetailsVoList);
        List<HotelOrderAssist> hotelOrderAssists = hotelOrderAssistMapper.selectHotelOrderAssistListByOrderId(hotelOrder.getOrderid());
        map.put("hotelOrderAssist", hotelOrderAssists);
        return map;
    }

    /**
     * 会员常用旅客信息列表
     * */
    @Override
    public List<CustomerTraveler> CustomerTraveler(Long memberId) {
        List<CustomerTraveler> travelerList = remoteCustomerService.CustomerTravelerList(memberId);
        if (travelerList != null && travelerList.size() > 0){
            return  travelerList;
        }
        else {
            return null;
        }
    }

    /**
     * 查询酒店图片
     * */
    @Override
    public List<HotelPicPathVo> selectPicPath(OrderHotelInput input) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        List<HotelPicPathVo> hotelPicPathVoList = new ArrayList<>();

        List<String> graphicIntroductionList = new ArrayList<>();

        HotelInfo hotelInfo = hotelInfoMapper.selectIntroduce(Long.valueOf(input.HotelIds));
        if (hotelInfo == null){
            throw new Exception("没有酒店图片");
        }

        if (hotelInfo.getSellingPoint() != null && !hotelInfo.getSellingPoint().equals("")){
            graphicIntroductionList.add(hotelInfo.getSellingPoint());
        }
        if (hotelInfo.getHouseIntro() != null && !hotelInfo.getHouseIntro().equals("")){
            String[] split = hotelInfo.getHouseIntro().split("lt;brgt;");
            for (String houseIntro : split) {
                graphicIntroductionList.add(houseIntro);
            }
        }
        Calendar calendar = Calendar.getInstance();
        /** 调用酒店详情接口 */
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        hotelDetailInput.ArrivalDate = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        hotelDetailInput.DepartureDate = format.format(calendar.getTime());
        hotelDetailInput.HotelIds = input.HotelIds;
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }


        /** 判断接口是否有酒店图片信息 */
        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                for (int i = 0 ; i < image.getLocations().size() ; i++) {
                    if (image.getLocations().get(i).getUrl() != null && !image.getLocations().get(i).getUrl().equals("")){
                        HotelPicPathVo hotelPicPathVo = new HotelPicPathVo();
                        hotelPicPathVo.setPicPath(image.getLocations().get(i).getUrl());
                        if ((i + 1) <= graphicIntroductionList.size()){
                            hotelPicPathVo.setPicPathIntroduce(graphicIntroductionList.get(i));
                        }
                        else {
                            hotelPicPathVo.setPicPathIntroduce(graphicIntroductionList.get(((i + 1) % graphicIntroductionList.size())));
                        }
                        hotelPicPathVoList.add(hotelPicPathVo);
                    }
                    else {//接口未返回酒店图片
                        HotelVo hotelVo = hotelMapper.selectPicPath(Long.valueOf(input.HotelIds));
                        HotelPicPathVo hotelPicPathVo = new HotelPicPathVo();
                        hotelPicPathVo.setPicPath(hotelVo.getPicPath());
                        for (String graphicIntroduction : graphicIntroductionList) {
                            if (graphicIntroduction != null && !graphicIntroduction.equals("")){
                                hotelPicPathVo.setPicPathIntroduce(graphicIntroduction);
                                break;
                            }
                        }
                        hotelPicPathVoList.add(hotelPicPathVo);
                    }
                }
            }
        }
        return hotelPicPathVoList;
    }

    /**
     * 酒店图片
     * */
    @Override
    public List<HotelPicPathVo> hotelPicture(OrderHotelInput input) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<HotelPicPathVo> hotelPicPathVoList = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        /** 调用酒店详情接口 */
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        hotelDetailInput.ArrivalDate = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        hotelDetailInput.DepartureDate = format.format(calendar.getTime());
        hotelDetailInput.HotelIds = input.HotelIds;
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        /** 判断接口是否有酒店图片信息 */
        for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels()) {
            for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                for (int i = 0 ; i < image.getLocations().size() ; i++) {
                    if (hotelPicPathVoList.size() < 10){
                        if (image.getLocations().get(i).getUrl() != null && !image.getLocations().get(i).getUrl().equals("")){
                            HotelPicPathVo hotelPicPathVo = new HotelPicPathVo();
                            hotelPicPathVo.setPicPath(image.getLocations().get(i).getUrl());
                            hotelPicPathVoList.add(hotelPicPathVo);
                        }
                        else {//接口未返回酒店图片
                            HotelVo hotelVo = hotelMapper.selectPicPath(Long.valueOf(input.HotelIds));
                            HotelPicPathVo hotelPicPathVo = new HotelPicPathVo();
                            hotelPicPathVo.setPicPath(hotelVo.getPicPath());
                            hotelPicPathVoList.add(hotelPicPathVo);
                        }
                    }
                    else {
                        break;
                    }
                }
            }
        }
        return hotelPicPathVoList;
    }

    /**
     * 查询酒店图片
     * */
    @Override
    public List<PicPathVo> selectPicPathVo(OrderHotelInput input) throws Exception {
        List<PicPathVo> picPathVoList = new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        /** 调用酒店详情接口 */
        HotelDetailInput hotelDetailInput = new HotelDetailInput();
        hotelDetailInput.ArrivalDate = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        hotelDetailInput.DepartureDate = format.format(calendar.getTime());
        hotelDetailInput.HotelIds = input.HotelIds;
        HotelDetailOutput hotelDetailOutput;
        try {
            hotelDetailOutput = ElongUtils.queryByIdHotel(hotelDetailInput);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        PicPathVo picPathVo = picPathVo(hotelDetailOutput);
        picPathVoList.add(picPathVo);

        return picPathVoList;
    }

    public PicPathVo picPathVo(HotelDetailOutput hotelDetailOutput)
    {
        int[] pinPathType = {1, 2, 3, 5, 6, 8, 10, 11, 12};
        PicPathVo picPathVo = new PicPathVo();
        List<PicPath> picPathList = new ArrayList<>();
        int picPathNum = 0;//图片总数

        //遍历酒店详细信息
        if (hotelDetailOutput.Result != null)
        {
            for (HotelDetailResponse.HotelsBean hotel : hotelDetailOutput.Result.getHotels())
            {
                //遍历图片类型
                for (int type : pinPathType)
                {
                    PicPath picPath = new PicPath();
                    List<PathVo> pathVoList = new ArrayList<>();

                    String pathType = pinPathType(type);
                    picPath.setPicPathType(pathType);
                    if (hotel.getImages() != null && hotel.getImages().size() > 0)
                    {
                        List<HotelDetailResponse.HotelsBean.Images> imagesList = hotel.getImages().stream().filter(images -> images.getType() == type).collect(Collectors.toList());
                        for (HotelDetailResponse.HotelsBean.Images images : imagesList)
                        {
                            picPathNum = picPathNum + images.getLocations().size();
                            PathVo pathVo = new PathVo();
                            pathVo.setPicPathUrl(images.getLocations().get(0).getUrl());

                            //图片对应的房型id,为空则显示图片类型
                            if (images.getRoomId() != null && !images.getRoomId().equals(""))
                            {
                                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms())
                                {
                                    if (images.getRoomId().equals(room.getRoomId()))
                                    {
                                        pathVo.setPicPathRoomType(room.getName());
                                        break;
                                    }
                                }
                            } else
                            {
                                pathVo.setPicPathRoomType(pathType);
                            }
                            if (pathVoList.size() >= 10)
                            {
                                break;
                            }
                            pathVoList.add(pathVo);
                            picPath.setPathVoList(pathVoList);
                        }
                    }

                    //遍历图片集合
                /*for (HotelDetailResponse.HotelsBean.Images image : hotel.getImages()) {
                    picPathNum = picPathNum + image.getLocations().size();
                    PathVo pathVo = new PathVo();

                    //判断图片类型与集合记录的类型是否相等
                    if (image.getType() == type){
                        //遍历图片url
                        for (HotelDetailResponse.HotelsBean.Images.Locations location : image.getLocations()) {
                            pathVo.setPicPathUrl(location.getUrl());

                            //图片对应的房型id,为空则显示图片类型
                            if (image.getRoomId() != null && !image.getRoomId().equals("")){
                                for (HotelDetailResponse.HotelsBean.RoomsBean room : hotel.getRooms()) {
                                    if (image.getRoomId().equals(room.getRoomId())){
                                        pathVo.setPicPathRoomType(room.getName());
                                        break;
                                    }
                                }
                            }
                            else {
                                pathVo.setPicPathRoomType(pathType);
                            }
                            if (pathVoList.size() >= 2){
                                break;
                            }
                            pathVoList.add(pathVo);
                            picPath.setPathVoList(pathVoList);
                        }
                    }
                }*/
                    picPathList.add(picPath);
                }
            }
        }
        picPathVo.setPicPathNum(picPathNum);
        picPathVo.setPicPathList(picPathList);
        return picPathVo;
    }

    /**
     * 艺龙查询酒店列表
     * @param conditionVo
     * @return
     */
    public HotelDetailOutput queryByIdHotelList(ConditionVo conditionVo) {
        HotelDetailOutput hotelDetailOutput = new HotelDetailOutput();
        //获取艺龙城市id
        HotelElongCity hotelElongCity = hotelElongCityMapper.selectHotelElongCityByJsjcityname(conditionVo.getCityName());
        if (hotelElongCity != null) {
            conditionVo.setCityId(hotelElongCity.getElongcityid());
            //该1 2 3 4 为固定值 默认为1 2 4，3为需要接口返回Images集合
            conditionVo.setResultType("1,2,3,4");
            hotelDetailOutput = (HotelDetailOutput) getResult(hotelDetailOutput, conditionVo, HotelUtils.HOTEL_LIST);
            return hotelDetailOutput;
        }
        else {
            return null;
        }
    }

    /**
     * 订单状态
     * */
    public String orderStatus(Long showstatus){
        String showStatus = null;

        if (showstatus == HotelOrderStatus.Status.TOBECONFIRMED.getCode()) {
            showStatus = HotelOrderStatus.Status.TOBECONFIRMED.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.CONFIRM.getCode()) {
            showStatus = HotelOrderStatus.Status.CONFIRM.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.NOTICE.getCode()) {
            showStatus = HotelOrderStatus.Status.NOTICE.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.AUDIT.getCode()) {
            showStatus = HotelOrderStatus.Status.AUDIT.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.COMPLETE.getCode()) {
            showStatus = HotelOrderStatus.Status.COMPLETE.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.NOSHOW.getCode()) {
            showStatus = HotelOrderStatus.Status.NOSHOW.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.CANCEL.getCode()) {
            showStatus = HotelOrderStatus.Status.CANCEL.getValue();
        }
        else if (showstatus == HotelOrderStatus.Status.INVALID.getCode()) {
            showStatus = HotelOrderStatus.Status.INVALID.getValue();
        }

        return showStatus;
    }

    /**
     * 支付方式
     * */
    public String paymentTypes(Long paytype){
        String payType = null;

        if (paytype == 1){
            payType = "信用卡";
        }
        else if (paytype == 2){
            payType = "银联语音";
        }
        else if (paytype == 3){
            payType = "微信支付";
        }
        else if (paytype == 4){
            payType = "支付宝";
        }
        else if (paytype == 5){
            payType = "差旅";
        }
        else if (paytype == 0){
            payType = "非卡";
        }
        else if (paytype == 6){
            payType = "储蓄卡";
        }
        else if (paytype == 75){
            payType = "一网通";
        }
        else if (paytype == 10){
            payType = "快钱";
        }
        else if (paytype == 20){
            payType = "网银";
        }
        else if (paytype == 30){
            payType = "易宝";
        }
        else if (paytype == 40){
            payType = "汇款";
        }
        else if (paytype == 50){
            payType = "银联卡";
        }

        return payType;
    }

    /**
     * 图片类型
     * */
    public String pinPathType(int pinPath){
        String pinPathType = null;
        switch (pinPath){
            case 1:
                pinPathType = HotelEnum.RegionalLocation.Restaurant.getValue();
                break;
            case 2:
                pinPathType = HotelEnum.RegionalLocation.RecreationFacilities.getValue();
                break;
            case 3:
                pinPathType = HotelEnum.RegionalLocation.Meeting.getValue();
                break;
            case 5:
                pinPathType = HotelEnum.RegionalLocation.Exterior.getValue();
                break;
            case 8:
                pinPathType = HotelEnum.RegionalLocation.GuestRoom.getValue();
                break;
            case 6:
                pinPathType = HotelEnum.RegionalLocation.LobbyReception.getValue();
                break;
            case 10:
                pinPathType = HotelEnum.RegionalLocation.OtherFacilities.getValue();
                break;
            case 11:
                pinPathType = HotelEnum.RegionalLocation.PublicArea.getValue();
                break;
            case 12:
                pinPathType = HotelEnum.RegionalLocation.NearbyAttractions.getValue();
                break;
        }
        return pinPathType;
    }

    /**
     * 添加酒店异常订单
     * */
    public int hotelOrderException(String person, Long customerId, String personPhone, String hotelName, String exceptionInfo, String sourceWay, String orderId, Long employeeId){
        HotelOrderException hotelOrderException = new HotelOrderException();
        hotelOrderException.setPerson(person);
        hotelOrderException.setPersonPhone(personPhone);
        hotelOrderException.setHotelName(hotelName);
        hotelOrderException.setReserveTime(new Date());
        hotelOrderException.setExceptionInfo(exceptionInfo);
        hotelOrderException.setSourceWay(sourceWay);
        hotelOrderException.setStatus("untreated");
        hotelOrderException.setOrderId(orderId);
        hotelOrderException.setOrderType("reserve");
        hotelOrderException.setEmployeeId(employeeId);
        hotelOrderException.setCustomerId(customerId);
        int i = hotelOrderExceptionMapper.insertHotelOrderException(hotelOrderException);
        return i;
    }

    /**
     * 验证酒店取消状态
     * */
    public boolean cancelStart(Long id) throws Exception {
        OrderIdCondition condition = new OrderIdCondition();
        condition.setOrderId(id);
        OrderDetailResult orderDetailResult = ElongUtils.orderDetail(condition);
        if (orderDetailResult != null && orderDetailResult.Result != null && orderDetailResult.Result.Status != null){
            HotelOrder hotelOrder = new HotelOrder();
            hotelOrder.setELongOrderId(id);
            hotelOrder.seteLongStart(orderDetailResult.Result.Status);
            int i = hotelOrderMapper.updateHotelOrder(hotelOrder);
            if (i <= 0){
                throw new Exception("添加艺龙订单状态枚举失败");
            }
            if (orderDetailResult.Result.Status.equals("D") && orderDetailResult.Result.Status.equals("E")){
                return true;
            }
            else {
                return false;
            }
        }
        else {
            throw new Exception("未查到艺龙酒店订单信息");
        }
    }

    /**
     * 根据日期获取 星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public String conversionDate(String date) {
        switch (date) {
            case "星期一":
                date = "1";
                break;
            case "星期二":
                date = "2";
                break;
            case "星期三":
                date = "3";
                break;
            case "星期四":
                date = "4";
                break;
            case "星期五":
                date = "5";
                break;
            case "星期六":
                date = "6";
                break;
            case "星期日":
                date = "7";
                break;
        }
        return date;
    }

    /**
     * 根据传入的日期,获取时间区间中所有的日期
     *
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return java.util.List<java.time.LocalDate>
     */
    public static List<LocalDate> getAllDatesInTheDateRange(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> localDateList = new ArrayList<>();
        // 开始时间必须小于结束时间
        if (startDate.isAfter(endDate)) {
            return null;
        }
        while (startDate.isBefore(endDate)) {
            localDateList.add(startDate);
            startDate = startDate.plusDays(1);
        }
        localDateList.add(endDate);
        return localDateList;
    }

    /**
     * 早餐处理
     * @param breakfast
     * @param valueAdd
     * @param typeCode
     * @return
     */
    public String valueAdd(String breakfast, HotelDetailResponse.HotelsBean.ValueAdd valueAdd, String typeCode) {
        String valueAddId = "";
        if (breakfast.equals(HotelEnum.RegionalLocation.WithoutBreakfast.getValue())) {//不含早
            if (!typeCode.equals("")) {
                if (valueAdd.getTypeCode().equals(typeCode) && String.valueOf(valueAdd.isInclude()).equals("false") && valueAdd.getAmount() == 0) {
                    valueAddId = valueAdd.getValueAddId();
                }
            } else {
                if (String.valueOf(valueAdd.isInclude()).equals("false") && valueAdd.getAmount() == 0) {
                    valueAddId = valueAdd.getValueAddId();
                }
            }
        } else if (breakfast.equals(HotelEnum.RegionalLocation.BreakfastIncluded.getValue())) {//含早餐
            if (!typeCode.equals("")) {
                if (valueAdd.getTypeCode().equals(typeCode) && String.valueOf(valueAdd.isInclude()).equals("true")) {
                    valueAddId = valueAdd.getValueAddId();
                }
            } else {
                if (String.valueOf(valueAdd.isInclude()).equals("true")) {
                    valueAddId = valueAdd.getValueAddId();
                }
            }
        } else {
            if (!typeCode.equals("")) {
                if (valueAdd.getTypeCode().equals(typeCode) && breakfast.equals(HotelEnum.RegionalLocation.SingleBreakfast.getValue())) {//单人早餐
                    if (valueAdd.getAmount() == 1) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                } else if (valueAdd.getTypeCode().equals(typeCode) && breakfast.equals(HotelEnum.RegionalLocation.BreakfastForTwo.getValue())) {//双人早餐
                    if (valueAdd.getAmount() == 2) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                } else if (valueAdd.getTypeCode().equals(typeCode) && breakfast.equals(HotelEnum.RegionalLocation.Above.getValue())) {//含三早及以上
                    if (valueAdd.getAmount() >= 3) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                }
            } else {
                if (breakfast.equals(HotelEnum.RegionalLocation.SingleBreakfast.getValue())) {//单人早餐
                    if (valueAdd.getAmount() == 1) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                } else if (breakfast.equals(HotelEnum.RegionalLocation.BreakfastForTwo.getValue())) {//双人早餐
                    if (valueAdd.getAmount() == 2) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                } else if (breakfast.equals(HotelEnum.RegionalLocation.Above.getValue())) {//含三早及以上
                    if (valueAdd.getAmount() >= 3) {
                        valueAddId = valueAdd.getValueAddId();
                    }
                }
            }
        }
        return valueAddId;
    }
}